我有两个文本文件,名称是 one.txt 和 Two.txt
在 one.txt 中,内容是
AAA
BBB
CCC
DDD
在two.txt中,内容是
DDD
EEE
我想要一个Python代码来确定one.txt中是否存在two.txt的包含
如果存在意味着不执行任何操作,但是如果two.txt 的内容不存在意味着它应该附加到one.txt
我想要 one.txt 中的输出为
AAA
BBB
CCC
DDD
EEE
Code:
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 https://docs.python.org/2.7/library/stdtypes.html#set-types-set-frozenset,因为它会为您处理重复项
Edit
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)
Edit 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'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)