Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 搜索列表1中的单词,如果匹配,则从列表2中删除单词_Python 3.x_File_Loops_Text Files_Word List - Fatal编程技术网

Python 3.x 搜索列表1中的单词,如果匹配,则从列表2中删除单词

Python 3.x 搜索列表1中的单词,如果匹配,则从列表2中删除单词,python-3.x,file,loops,text-files,word-list,Python 3.x,File,Loops,Text Files,Word List,我有两个长长的列表,里面有一个txt中的单词。文件在其中一个句子中有几行。如果第二个列表中的单词出现在一个句子中,我需要删除它 Titels.txt: Samsung SM-G960F S9 Samsung SM-G950F S8 Iphone A1906 8 Samsung SM-G940F S7 Remove.txt(“要删除的单词”): New_Titels.txt(它的外观): 我尝试过这段代码,但似乎输出了与以前相同的数据 infle=“C:/Users/user1/Desktop/

我有两个长长的列表,里面有一个txt中的单词。文件在其中一个句子中有几行。如果第二个列表中的单词出现在一个句子中,我需要删除它

Titels.txt:

Samsung SM-G960F S9
Samsung SM-G950F S8
Iphone A1906 8
Samsung SM-G940F S7
Remove.txt(“要删除的单词”):

New_Titels.txt(它的外观):

我尝试过这段代码,但似乎输出了与以前相同的数据

infle=“C:/Users/user1/Desktop/Titels.txt”
delfile=“C:/Users/user1/Desktop/Remove.txt”
outfile=“C:/Users/user1/Desktop/New_Titels.txt”
fdel=打开(delfile)
翅片=打开(填充)
fout=打开(输出文件,“w+”)
对于fin中的行:
对于fdel中的单词:
行=行。替换(单词“”)
四、写(行)
财务结束()
fout.close()

将多次调用
delfile
的for循环,因此您需要多次读取此文件。问题是,在第一次读取文件后,需要将其重置以再次读取。要重置它,请使用
f.seek(0)
重新定位到文件的开头,或者关闭它,然后再次打开它,它将从文件的开头开始。或者,您可以将
与open(filename)
一起使用,这样每次读取文件时都会自动关闭文件。此外,使用
word.strip()
删除每行末尾的换行符

for line in fin:
    with open(delfile) as words:
        for word in words:
            line = line.replace(word.strip(), "")
    fout.write(line)

正如我在评论中所说,有两个问题,
word
上有一个新行,
fdel
文件正在迭代两次,请尝试立即读取单词

foo = open('foo')
bar = open('bar').readlines()

for line in foo:
    for word in bar:
        line = line.replace(word.strip(), '')
    print(line.strip())
您还可以使用和打开多个文件,这些文件将被关闭 当带的
块完成时

with open('foo') as fin, open('bar') as bar:
   ...

这将避免忘记调用close

word如果包含新行,请尝试
line.replace(work.strip(),'')
也将在fdel上迭代多次,而不是一次尝试readlines
fdel=open(delfile).readlines()
foo = open('foo')
bar = open('bar').readlines()

for line in foo:
    for word in bar:
        line = line.replace(word.strip(), '')
    print(line.strip())
with open('foo') as fin, open('bar') as bar:
   ...