gpt4 book ai didi

python - 如何在python中比较和合并两个文件

转载 作者:太空宇宙 更新时间:2023-11-04 07:58:59 24 4
gpt4 key购买 nike

我有两个文本文件,名称分别是 one.txt 和 two.txt在 one.txt 中,内容是

AAA
BBB
CCC
DDD

在two.txt中,内容是

DDD
EEE

我想要一个 python 代码来确定包含 two.txt 是否存在于 one.txt 中如果存在意味着什么都不做,但是如果 two.txt 的内容不存在意味着它应该附加到 one.txt

我想要 one.txt 中的输出为

AAA
BBB
CCC
DDD
EEE

代码:

file1 = open("file1.txt", "r") 
file2 = open("file2.txt", "r")
file3 = open("resultss.txt", "w")
list1 = file1.readlines()
list2 = file2.readlines()
file3.write("here: \n")
for i in list1: for j in list2:
if i==j: file3.write(i)

最佳答案

sets 很简单,因为它会为您处理重复项

编辑

with open('file1.txt',"a+") as file1, open('file2.txt') as file2:
new_words = set(file2) - set(file1)
if new_words:
file1.write('\n') #just in case, we don't want to mix to words together
for w in new_words:
file1.write(w)

编辑2

如果顺序很重要,请使用 Max Chretien 的答案。

如果想知道常用词,可以用交集

with open('file1.txt',"a+") as file1, open('file2.txt') as file2:
words1 = set(file1)
words2 = set(file2)
new_words = words2 - words1
common = words1.intersection(words2)
if new_words:
file1.write('\n')
for w in new_words:
file1.write(w)
if common:
print 'the commons words are'
print common
else:
print 'there are no common words'

关于python - 如何在python中比较和合并两个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43871417/

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