【问题标题】:Cleaning URLs and saving them to txt file Python3清理 URL 并将它们保存到 txt 文件 Python3
【发布时间】:2021-02-10 21:42:38
【问题描述】:

我正在尝试清理和规范化文本文件中的 URL。

这是我当前的代码:

import re

with open("urls.txt", encoding='utf-8') as f:
    content = f.readlines()
content = [x.strip() for x in content]

url_format = "https://www.google"
for item in content:
    if not item.startswith(url_format):
        old_item = item
        new_item = re.sub(r'.*google', url_format, item)
        content.append(new_item)
        content.remove(old_item)

with open('result.txt', mode='wt', encoding='utf-8') as myfile:
    myfile.write('\n'.join(content))

问题是,如果我在循环中打印旧项目和新项目,它会显示每个 URL 都已被清理。但是当我在循环之外打印我的 URL 列表时,这些 URL 仍然没有被清理,其中一些被删除,而另一些则没有。

请问为什么当我在 for 循环中删除错误的 URL 并添加清理后的 URL 时,它们仍然在列表中?也许这应该以不同的方式解决?

另外,我注意到对于大量 URL,代码运行需要很长时间,也许我应该使用不同的工具?

任何帮助将不胜感激。

【问题讨论】:

    标签: python python-3.x url normalization normalize


    【解决方案1】:

    这是因为您在迭代列表时从列表中删除项目,这是一件坏事,您可以创建另一个具有新值的列表并附加到它,或者使用索引就地修改列表,您也可以只使用列表推导来完成此任务:

    content = [item if item.startswith(url_format) else re.sub(r'.*google', url_format, item) for item in content]
    

    或者,使用另一个列表:

    new_content = []
    
    for item in content:
        if item.startswith(url_format):
            new_content.append(item)
        else:
            new_content.append(re.sub(r'.*google', url_format, item))
    

    或者,使用索引就地修改列表:

    for i, item in enumerate(content):
        if not item.startswith(url_format):
            content[i] = re.sub(r'.*google', url_format, item)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      • 2013-12-18
      • 1970-01-01
      • 1970-01-01
      • 2020-06-27
      相关资源
      最近更新 更多