【发布时间】:2019-09-15 01:10:13
【问题描述】:
我有两个长长的列表,其中包含 txt 中的单词。文件。其中之一是带有句子的线条。如果第二个列表中的单词在其中一个句子中找到,我需要将其删除。
Titels.txt:
Samsung SM-G960F S9
Samsung SM-G950F S8
Iphone A1906 8
Samsung SM-G940F S7
Remove.txt(“要删除的单词”):
SM-G960F
SM-G950F
A1906
SM-G940F
A1904
SM-G930F
New_Titels.txt(它的样子):
Samsung S9
Samsung S8
Iphone 8
Samsung S7
我试过这段代码,但输出的数据似乎和以前一样。
infile = "C:/Users/user1/Desktop/Titels.txt"
delfile = "C:/Users/user1/Desktop/Remove.txt"
outfile = "C:/Users/user1/Desktop/New_Titels.txt"
fdel = open(delfile)
fin = open(infile)
fout = open(outfile, "w+")
for line in fin:
for word in fdel:
line = line.replace(word, "")
fout.write(line)
fin.close()
fout.close()
【问题讨论】:
-
word 换行,试试
line.replace(work.strip(), '') -
也将迭代 fdel 而不是一次尝试 readlines
fdel = open(delfile).readlines()
标签: python-3.x file loops text-files word-list