【问题标题】:How can I find a line according with two subsequent words in a text file如何根据文本文件中的两个后续单词找到一行
【发布时间】:2026-01-25 21:30:01
【问题描述】:

我对 Python 很陌生,所以请原谅无知的问题或过于复杂的代码。 :) 我非常感谢您的帮助。

我目前的代码是打开读取一个/几个文本文件,根据关键字搜索行 然后写一个新的文本文件,同时省略找到关键字的行。这是为了在分析剩余文本之前清理我不想拥有的信息文件(报纸文章)。问题是我只能搜索单个单词。但是,有时我想搜索特定的单词组合,即不仅仅是“Rechte”,而是“Alle Rechte vorbehalten”。 如果我将它保存到我的 delword-list 中,它就不起作用(我认为因为 line.split 中的部分只检查单个单词。)

非常感谢任何帮助!

    import os
    
    delword = ['Quelle:', 'Ressort:', 'Ausgabe:', 'Dokumentnummer:', 'Rechte', 'Alle Rechte vorbehalten']
    
    path = r'C:\files'
    pathnew = r'C:\files\new'
    
    dir = []
    
    for f in os.listdir(path):
        if f.endswith(".txt"):
            #print(os.path.join(path, f))
            print(f)
            if f not in dir:
                dir.append(f)
             
    for f in dir:
        
        fpath = os.path.join(path, f)
        print (fpath)
        fopen = open(fpath, encoding="utf-8", errors='ignore')
        printline = True
        #print(fopen.read())
        fnew = 'clean' + f
        fpathnew = os.path.join(pathnew, fnew)
    
        with open(fpath, encoding="utf-8", errors='ignore') as input:
            with open(fpathnew, "w", errors='ignore') as output: 
                for line in input:
                    printline = True
                    for part in line.split():
                        for i in range(len(delword)):
                                if delword [i] in part:
                                    #line = " ".join((line).split())
                                    printline = False
                                    #print('Found: ', line)
                    if printline == False:
                        output.write('\n')
                    if printline == True:
                        output.write(line)
                    
        
        input.close()
        output.close()
        fopen.close()

【问题讨论】:

    标签: python search text word


    【解决方案1】:

    对于这种特殊情况 - 您不需要拆分线路。您可以使用

    运行类似的检查
    for line in input:
        for word in delword:
            if word in line: ...
    

    正如旁注:通常更通用或更复杂的问题将使用正则表达式,作为为此类处理创建的工具

    【讨论】: