比较两个文本文件,并删除python中的重复项 [英] comparing two text files and remove duplicates in python
问题描述
我有两个文本文件, file1
和 file2
。
I have two text files, file1
and file2
.
File1
包含一堆随机单词, file2
包含我要从 file1
发生时。
有没有办法这样做?
File1
contains a bunch of random words, and file2
contains words that I want to remove from file1
when they occur.
Is there a way of doing this?
我知道我可能应该自己尝试一个脚本,至少显示努力,但要诚实这是可笑的,不会有任何帮助。
I know I probably should include my own attempt at a script, to at least show effort, but to be honest it's laughable and wouldn't be of any help.
如果有人至少可以提供关于从哪里开始的提示,那将是非常感激的。 b $ b
If someone could at least give a tip about where to start, it would be greatly appreciated.
推荐答案
得到每个单词:
f1 = open("/path/to/file1", "r")
f2 = open("/path/to/file2", "r")
file1_raw = f1.read()
file2_raw = f1.read()
file1_words = file1_raw.split()
file2_words = file2_raw.split()
如果您想要file1中不在file2中的唯一字词:
if you want unique words from file1 that aren't in file2:
result = set(file1_words).difference(set(file2_words))
如果您关心从file2_words中的文件file1中删除单词
if you care about removing the words from the text of file1
for w in file2_words:
file1_raw = file1_raw.replace(w, "")
这篇关于比较两个文本文件,并删除python中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!