問題描述
我有兩個文本文件,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.
如果有人至少可以提供關于從哪里開始的提示,將不勝感激.
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 = f2.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))
如果您關心從 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中的重復項的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!