【问题标题】:Remove certain links from a textfile by reading textfile通过读取文本文件从文本文件中删除某些链接
【发布时间】:2022-01-25 15:35:18
【问题描述】:

所以我有包含一些链接的 whitelist.txt 和包含其他链接的 scrapedlist.txt 以及 whitelist.txt 中的链接。

我正在尝试打开并阅读 whitelist.txt,然后打开并阅读 scrapedlist.txt - 写入新文件 updatedlist2.txt 将包含 scrapedlist.txt 减去 whitelist.txt.

的所有内容

我对 Python 还是很陌生,所以还在学习。我已经搜索了答案,这就是我想出的:

def whitelist_file_func():
    with open("whitelist.txt", "r") as whitelist_read:
        whitelist_read.readlines()
    whitelist_read.close()

    unique2 = set()

    with open("scrapedlist.txt", "r") as scrapedlist_read:
        scrapedlist_lines = scrapedlist_read.readlines()
    scrapedlist_read.close()

    unique3 = set()

    with open("updatedlist2.txt", "w") as whitelist_write2:
   
        for line in scrapedlist_lines:
            if unique2 not in line and line not in unique3:
                whitelist_write2.write(line)
                unique3.add(line)

我收到此错误,我也不确定我是否以正确的方式进行操作:

if unique2 not in line and line not in unique3:
TypeError: 'in <string>' requires string as left operand, not set

我应该怎么做才能实现上述以及我的代码是否正确?

编辑:

whitelist.txt:

KUWAIT
ISRAEL
FRANCE

scrapedlist.txt:

USA
CANADA
GERMANY
KUWAIT
ISRAEL
FRANCE

updatedlist2.txt(应该是这样):

USA
CANADA
GERMANY

【问题讨论】:

  • unique2 的用途是什么?你甚至不用任何地方的值来填充它
  • 哦,那是存放whitelist.txt的行吗?我错了吗?
  • 你也永远不会对 whitelist_read.readlines() 做任何事情......你没有将它分配给任何东西。

标签: python text-files with-statement


【解决方案1】:

根据您的描述,我对您的代码进行了一些更改。

  1. readlines() 方法被替换为 read().splitlines()。他们都读取整个文件并将每一行转换为一个列表项。区别在于readlines() 在项目末尾包含\n
  2. unique2unique3 被删除。我找不到它们的用法。
  3. 前两个部分whitelist_linesscrapedlist_lines 是两个包含链接的列表。根据您的描述,我们需要不在whitelist_lines 列表中的scrapedlist_lines 行,因此条件if unique2 not in line and line not in unique3: 更改为if line not in whitelist_lines:
  4. 如果您使用的是 Python 2.5 及更高版本,则可以使用 with 语句自动为您调用 close()。

最终代码为:

with open("whitelist.txt", "r") as whitelist_read:
    whitelist_lines = whitelist_read.read().split("\n")
    
with open("scrapedlist.txt", "r") as scrapedlist_read:
    scrapedlist_lines = scrapedlist_read.read().split("\n")

with open("updatedlist2.txt", "w") as whitelist_write2:
    for line in scrapedlist_lines:
        if line not in whitelist_lines:
            whitelist_write2.write(line + "\n")

【讨论】:

  • 不,我们只需要 updatedlist2.txt 中的 scrapedlist.txt 减去 whitelist.txt 的内容,因为 scrapedlist.txt 也包含 whitelist.txt 的功能。
  • 我想我们都说同样的话。在编程方式代码计算updatedlist2.txt = scrapedlist.txt - whitelist.txt :) 请检查代码的输出,如果有问题。举例子告诉我。谢谢。
  • 您能否将文件的某些部分附加到问题中?我的意思是whitelist.txtscrapedlist.txt 文件。然后我们可以用真实数据进行测试。
  • 非常感谢 :) 祝你在 python 中度过美好时光:D
  • 无需关闭,因为您使用的是 with 上下文管理器。
猜你喜欢
  • 2010-12-26
  • 2014-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多