gpt4 book ai didi

python - 比较两个文件中的行,如果相等则删除

转载 作者:行者123 更新时间:2023-11-30 22:49:41 24 4
gpt4 key购买 nike

我正在打开两个文件 - 一个包含用于比较的新文件,另一个包含我需要从此文件中删除的流行语。到目前为止我已经将其作为一个函数:

def remove(file, buzz):
#outer for loop cycles through the buzz file
for line in buzz:
#inner for loop cycles through the new file
for line2 in file:
if (line==line2):
file.remove(line2)
else:
continue

其中 file 是在 main() 中打开的新文件并传递给此,并且 buzz是正在打开并从 main() 传递的嗡嗡声文件.

删除部分不起作用,新文件不会更改。

有什么建议吗?

最佳答案

首先读取每个文件的内容并将它们放入列表中:

a_list = open(file_a).read().splitlines()
b_list = open(file_b).read().splitlines()

然后删除a_list中b_list中的单词:

a_list = [word for word in a_list if word not in b_list]

a_list 现在仅包含 b_list 中没有的单词

关于python - 比较两个文件中的行,如果相等则删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39664556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com