【发布时间】: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()
【问题讨论】: