![](/img/trans.png)
[英]how can i search a text file of list of words from user input and print the line which contains these words?
[英]How can I find a line according with two subsequent words in a text file
我对 Python 很陌生,所以请原谅无知的问题或过于复杂的代码。 :) 我非常感谢任何帮助。
到目前为止,我所拥有的代码是打开读取一个/几个文本文件,根据关键字搜索行,然后编写一个新的文本文件,同时省略包含找到的关键字的行。 这是为了在分析剩余文本之前清除我不想拥有的信息文件(报纸文章)。 问题是我只能搜索单个单词。 但是,有时我想搜索特定的单词组合,即不仅仅是“Rechte”,而是“Alle Rechte vorbehalten”。 如果我将它保存到我的 delword 列表中,它就不起作用(我认为是因为 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()
对于这种特殊情况 - 您不需要分割线。 您可以运行类似的检查
for line in input:
for word in delword:
if word in line: ...
正如旁注:通常更通用或更复杂的问题将使用正则表达式,作为为此类处理创建的工具
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.