Python在文本文件中搜索关键字,并打印多个关键字的关联行

Python在文本文件中搜索关键字,并打印多个关键字的关联行,python,text-extraction,Python,Text Extraction,我试图在一个包含大量无关信息的.txt文件中搜索几个包含最重要信息的关键字。我想找到单词并打印出单词所在的行 我对python相当陌生,并认为我已经了解了它,但我不知道如何为多个关键字扩展当前代码 fileName = input("Paste file name here") with open(fileName) as inputFile: data = inputFile.readlines() inputFile.close() for i, line in enum

我试图在一个包含大量无关信息的.txt文件中搜索几个包含最重要信息的关键字。我想找到单词并打印出单词所在的行

我对python相当陌生,并认为我已经了解了它,但我不知道如何为多个关键字扩展当前代码

fileName = input("Paste file name here")

with open(fileName) as inputFile:
    data = inputFile.readlines()
    inputFile.close()

for i, line in enumerate(data):
    searchPhrase1 = input("what phrase are you looking for?")
    if searchPhrase1 in line:
        for l in data[i:i:3]:
            print (l)
print
您可以替换您的:

if searchPhrase1 in line:


这将检查列表中的每个项目,以查看行中是否存在。如果至少有一个匹配项,则任何函数都将返回true。

这里是我的一个旧python脚本,用于解析文本

它使用了一个小regx,但是应该可以让你到达你想去的地方

#!/usr/bin/python

import sys
import os
import re

def readFile( fileName ):
    try:
      file myFile = open( fileName, "r")
    except IOError:
      print "There was an error reading file"
      sys.exit()
    file_text = myFile.read()
    myFile.close()
    return file_text

def writeFile( fileName, fileContent ):
    ret = 1
    try:
        file myFile = open(fileName, "w")
    except IOError:
        print "There was an error writing to", fileName
        sys.exit()
    myFile.write(fileContent)
    myFile.close()
    return ret

str     textContents  = readFile("./myfile.txt")
list    textLineList = textContents.splitlines()

for textLine in textLineList:
    if re.match("(?:word1|word2|word3)*", textLine, re.I ):
        print textLine

为了进一步优化,可以预编译正则表达式。但是它应该已经是一个非常快的小脚本了。

如果第行中的searchPhrase1可以工作,假设该行包含的单词的顺序正好是这个顺序。你是说要查找包含任意顺序单词的行吗?还有,数据[i:i:3]
中l的
是怎么回事?为什么不直接打印(行)
?实际上我刚把它改成了打印行。不,我想搜索三个相互独立的单词。为了更透明,我正在用医学数据进行研究,并想找出任何不同的因素。例如,如果患者的病情检测呈阳性,则有一个评分系统,因此我将搜索该评分系统的名称,并打印行“患者有一个”在此处插入评分系统名称“得分为…”因为文件中就是这样写的。@JohnGordon抱歉忘了标记你我很抱歉也许我在编程方面还是太新了,但我希望它返回短语所在的行。是否以布尔值形式返回,或者如果为真,则将打印该行并以布尔值形式返回。因此,如果为True,它将进入if块内的下一行(应该是print(line))
#!/usr/bin/python

import sys
import os
import re

def readFile( fileName ):
    try:
      file myFile = open( fileName, "r")
    except IOError:
      print "There was an error reading file"
      sys.exit()
    file_text = myFile.read()
    myFile.close()
    return file_text

def writeFile( fileName, fileContent ):
    ret = 1
    try:
        file myFile = open(fileName, "w")
    except IOError:
        print "There was an error writing to", fileName
        sys.exit()
    myFile.write(fileContent)
    myFile.close()
    return ret

str     textContents  = readFile("./myfile.txt")
list    textLineList = textContents.splitlines()

for textLine in textLineList:
    if re.match("(?:word1|word2|word3)*", textLine, re.I ):
        print textLine