【发布时间】: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