实现两个文本内容去重,输出两个文本不重复的结果
两个测试文本内容如下
1.txt中内容为 1 2 3 4 5 6 7 8
2.txt中内容为 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
分别读取两个文本的内容
读取1.txt的内容,具体实现如下:
str1 = []
file_1 = open("1.txt","r",encoding="utf-8")
for line in file_1.readlines():
str1.append(line.replace("\n",""))
读取2.txt的内容,具体实现如下:
str2 = []
file_2 = open("2.txt", "r", encoding="utf-8")
for line in file_2.readlines():
str2.append(line.replace("\n", ""))
取出重复的内容
创建一个空列表,将两个文件中重复的内容取出来,具体实现如下:
str_dump = []
for line in str1:
if line in str2:
str_dump.append(line) #将两个文件重复的内容取出来
去掉重复内容
将两个文本的内容合并,去除重复的内容
str_all = set(str1 + str2) #将两个文件放到集合里,过滤掉重复内容
for i in str_dump:
if i in str_all:
str_all.remove(i) #去掉重复的文件
完整代码如下
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def file_qc():
str1 = []
file_1 = open("1.txt","r",encoding="utf-8")
for line in file_1.readlines():
str1.append(line.replace("\n",""))
str2 = []
file_2 = open("2.txt", "r", encoding="utf-8")
for line in file_2.readlines():
str2.append(line.replace("\n", ""))
str_dump = []
for line in str1:
if line in str2:
str_dump.append(line) #将两个文件重复的内容取出来
str_all = set(str1 + str2) #将两个文件放到集合里,过滤掉重复内容
for i in str_dump:
if i in str_all:
str_all.remove(i)#去掉重复的文件
for str in str_all: #去重后的结果写入文件
print(str)
with open("qc_V.txt","a+",encoding="utf-8") as f:
f.write(str + "\n")
if __name__=="__main__":
file_qc()
输出结果为
来源:https://www.cnblogs.com/dddjh/p/10753586.html