【问题标题】:Search for an Word in List 1 and remove words from a List 2 if they match在列表 1 中搜索单词,如果匹配,则从列表 2 中删除单词
【发布时间】: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


【解决方案1】:

delfile 的 for 循环将被多次调用,因此您需要多次读取此文件。问题是第一次读取文件后,需要重新设置才能再次读取。要重置它,可以使用f.seek(0) 重新定位到文件的开头,或者关闭它然后再次打开它,这将从文件的开头开始。或者,您可以使用with 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)

【讨论】:

    【解决方案2】:

    正如我在 cmets 中所说,有两个问题,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 打开多个文件,它们将被关闭 当with 块完成时

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

    这样可以避免忘记调用close

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      相关资源
      最近更新 更多