如何从Python中依赖于输入的函数创建for循环?

2024-04-25 15:21:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我终于掌握了Python的窍门,并开始在日常工作中使用它。然而,学习曲线仍然陡峭,我在尝试一些新的东西时遇到了障碍,我找到了一个代码here,用于从电报频道中删除成员。你知道吗

目前在第38-44行中,我们可以从列表中选择一个组,它将把用户数据刮入成员.csv. 你知道吗

编辑:解决了CSV命名问题:


    print('Saving In file...')
    print(target_group.title)
    filename = target_group.title 
    with open(("{}.csv".format(filename)),"w",encoding='UTF-8') as f:

我希望创建一个for循环,遍历列表中的每个组,而不是依赖于输入。你知道吗

print('Choose a group to scrape members from:')
i=0
for g in groups:
    print(str(i) + '- ' + g.title)
    i+=1 
g_index = input("Enter a Number: ")
target_group=groups[int(g_index)]

问题是我不确定如何用for循环替换这部分代码。你知道吗

不过,只要将其更改为for循环,就只会覆盖相同的内容成员.csv在每次迭代中,我计划对其进行更改,以便将其输出为唯一的文件。你知道吗

回到我的问题上来。我如何使这个单一的程序迭代循环通过所有的组,或者仅仅选择所有的组。你知道吗

谢谢你的帮助!你知道吗


Tags: csv代码target列表forindextitlegroup
2条回答

最终发现了问题:

命名CSV文件时:使用title属性命名文件并替换字符串。你知道吗

g_index = chat_num
target_group=groups[int(g_index)]
filename = target_group.title 
print('Fetching Members from {} ...'.format(filename))
all_participants = []
all_participants = client.get_participants(target_group, aggressive=True)

print('Saving In file...')
with open(("{}.csv".format(filename)),"w",encoding='UTF-8') as f:

为序列创建for循环时:原始代码(在问题中发布)不包含for循环。我的解决方案是从所有内容创建一个函数,然后遍历一个索引列表,该列表等于检测到的实例数量。最后看起来像这样:

chat_list_index = list(range(len(chats)))

for x in chat_list_index:
    try: 
        get(x)
    except:
        print("No more groups.", end = " ")
        pass
    pass
print("Done")

总的来说,这可能不是实现我所追求的目标的最佳解决方案,但是它现在对我来说已经足够好了,我学到了很多。也许将来会有人发现这是有益的。这里提供完整的代码:(https://github.com/ivanstruk/telegram-member-scraper/)。你知道吗

干杯!你知道吗

不能测试这个,但像这样的可能?这将为每个组创建一个新的.csv文件。你知道吗

for chat in chats:
    try:
        if chat.megagroup == True:
            groups.append(chat)
    except:
        continue

for current_group in groups:

    print(f"Fetching members for group \"{current_group.title}\"...")
    all_participants = client.get_participants(current_group, aggressive=True)

    current_file_name = f"members_{current_group.title}.csv"

    print(f"Saving in file \"{current_file_name}\"...")
    with open(current_file_name, "w+", encoding="UTF-8") as file:
        writer = csv.writer(file, delimiter=",", lineterminator="\n")
        writer.writerow(["username", "user id", "access hash", "name", "group", "group id"])
        for user in all_participants:
            username = user.username if user.username else ""
            first_name = user.first_name.strip() if user.first_name else ""
            last_name = user.last_name.strip() if user.last_name else ""
            name = f"{first_name} {last_name}"
            row = [username, user.id, user.access_hash, name, current_group.title, current_group.id]
            writer.writerow(row)
    print(f"Finished writing to file \"{current_file_name}\".")
print("Members scraped successfully.")

相关问题 更多 >