如何将结果保存在文本文件中?

huangapple go评论60阅读模式
英文:

How can I save the results in a text file?

问题

你尝试的是搜索Mojang API以获取所有可用的3/4字母用户名,但当我运行程序时,它运行了大约一小时然后停止,没有将结果保存到文本文件中,所以有人可以帮我将它们保存到我的桌面上的txt文件中吗?

代码:

import re
import requests as r
import itertools
from time import sleep

def check_name(name):
    url = "https://api.mojang.com/users/profiles/minecraft/{}"
    name_url = url.format(name)
    res = r.get(name_url)

    if res.status_code == 204:
        return True
    elif res.status_code == 200:
        return False
    elif res.status_code == 429:
        sleep(5)
        return check_name(name)

names = []
for i in itertools.product("abcdefghijklmnopqrstuvwxyz_0123456789", repeat=3):
    name = ""
    for ch in i:
        name += ch
    names.append(name)

for name in names:
    if check_name(name):
        f = open("names.txt", "a")
        f.write(f"{name}\n")

我尝试多次重写代码,但似乎没有任何效果,我也是Python的新手,所以可能是这个原因。

英文:

What I tried is to search the mojang API for all available 3/4 letter usernames, but when I launch the program it just runs for like an hour or so then stops, and does not save the results in a text file, so can someone help me with saving them to a txt file to my desktop?

Code:

import re
import requests as r
import itertools
from time import sleep



def check_name(name):
    url = "https://api.mojang.com/users/profiles/minecraft/{}"
    name_url = url.format(name)
    res = r.get(name_url)


    if res.status_code == 204:
        return True
    elif res.status_code == 200:
        return False
    elif res.status_code == 429:
        sleep(5)
        return(check_name(name))

names = []
for i in itertools.product("abcdefghijklmnopqrstuvwxyz_0123456789",repeat=3):
    name = ""
    for ch in i:
        name += ch
    names.append(name)

for name in names:
    if check_name(name):
        f = open("names.txt","a")
        f.write(f"{name}\n")

I tried to rewrite the code multiple times but nothing seemed to work, I'm also new to Python do probably that's why.

答案1

得分: 2

合并我的两条评论。没有必要将名称保存在列表中,只需在下一个循环中写出它们。您可以使用 ''.join(i) 将字符元组转换为字符串。因此,我会用以下代码替换最后两个循环:

with open("names.txt", "w") as fh:
    for i in itertools.product("abcdefghijklmnopqrstuvwxyz_0123456789", repeat=3):
        name = ''.join(i)
        if check_name(name):
            fh.write(name)
            fh.write("\n")
            fh.flush()

编辑:我添加了 fh.flush,因为我现在意识到您的 check_name 可能需要时间,而您希望文件正确反映当前的进度,而不受输出缓冲引起的延迟影响。

英文:

Combining my two comments. There is no need to save the names in a list to just write them out in the next loop. And you can convert the tuple of chars to a string with ''.join(i). So I would replace the last two loops with

with open("names.txt","w") as fh:
    for i in itertools.product("abcdefghijklmnopqrstuvwxyz_0123456789",repeat=3):
        name = ''.join(i)
        if check_name(name):
            fh.write(name)
            fh.write("\n")
            fh.flush()

EDIT: I added fh.flush since I now realize that your check_name may take time and you want the file to correctly reflect where you are right now without delays due to buffering of the output.

答案2

得分: 0

创建一个名为save_names的列表来存储可用的名字。
遍历名字列表,对于每个名字,调用check_name函数来确定它是否可用。如果可用,将其添加到save_names列表中。然后使用write方法将可用的名字列表中的名字写入文件。

import re
import requests as r
import itertools
from time import sleep

def check_name(name):
    url = "https://api.mojang.com/users/profiles/minecraft/{}"
    name_url = url.format(name)
    res = r.get(name_url)

    if res.status_code == 204:
        return True
    elif res.status_code == 200:
        return False
    elif res.status_code == 429:
        sleep(5)
        return check_name(name)

names = []
for i in itertools.product("abcdefghijklmnopqrstuvwxyz_0123456789", repeat=3):
    name = ""
    for ch in i:
        name += ch
    names.append(name)

save_names = []
for name in names:
    if check_name(name):
        save_names.append(name)

# 将结果保存到文本文件
with open("names.txt", "w") as f:
    f.write("\n".join(save_names))
英文:

Create a list save_names to store the names that are available.
Iterate through the names list, and for each name, call the check_name function to determine if it is available or not. If it is available, Add it to the save_names list. Then write the names in the available_names list to the file using the write method

import re
import requests as r
import itertools
from time import sleep

def check_name(name):
    url = "https://api.mojang.com/users/profiles/minecraft/{}"
    name_url = url.format(name)
    res = r.get(name_url)

    if res.status_code == 204:
        return True
    elif res.status_code == 200:
        return False
    elif res.status_code == 429:
        sleep(5)
        return check_name(name)

names = []
for i in itertools.product("abcdefghijklmnopqrstuvwxyz_0123456789", repeat=3):
    name = ""
    for ch in i:
        name += ch
    names.append(name)

save_names = []
for name in names:
    if check_name(name):
        save_names.append(name)

# Save results to a text file
with open("names.txt", "w") as f:
    f.write("\n".join(save_names))

答案3

得分: 0

我看到你的代码中有两个问题,第一个问题是当响应状态码为204时,你将其视为True,但这表示“无内容”。当状态码为“OK” 200 时,才应视为True,因此我修改了这部分。另外,你使用open()的方式不太准确,因为你没有关闭文件。相反,尝试使用带有关键字“with”的上下文。

import itertools
from time import sleep

import requests as r


def check_name(name):
    url = "https://api.mojang.com/users/profiles/minecraft/{}"
    name_url = url.format(name)
    res = r.get(name_url)

    if res.status_code == 200:
        return True
    elif res.status_code == 204:
        return False
    elif res.status_code == 429:
        sleep(5)
        return check_name(name)


names = []
for i in itertools.product("a", repeat=3):
    name = ""
    for ch in i:
        name += ch
    names.append(name)

with open("names.txt", "w") as file:
    for name in names:
        if check_name(name):
            file.write(f"{name}\n")

你可以采用类似Nadir建议的更好方法,但这段代码几乎与你提供的代码具有相同的逻辑。

英文:

I see two problems in your code, the first one is that you are considering a True case when the response is 204, which means "No content". When the status code is "OK" 200 is returned, so I modified that part. Now, the way you are using open() is not the most accurate option, cause you are not closing the file. Instead, try using context with the keyword "with"

import itertools
from time import sleep

import requests as r


def check_name(name):
    url = "https://api.mojang.com/users/profiles/minecraft/{}"
    name_url = url.format(name)
    res = r.get(name_url)

    if res.status_code == 200:
        return True
    elif res.status_code == 204:
        return False
    elif res.status_code == 429:
        sleep(5)
        return check_name(name)


names = []
for i in itertools.product("a", repeat=3):
    name = ""
    for ch in i:
        name += ch
    names.append(name)

with open("names.txt", "w") as file:
    for name in names:
        if check_name(name):
            file.write(f"{name}\n")

You can have better approaches like Nadir's suggestion, but this code has almost the same logic that in your code provided

huangapple
  • 本文由 发表于 2023年7月28日 04:39:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76783276.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定