【问题标题】:Python Search a text file for keyword and print the associated line for multiple keywordsPython 在文本文件中搜索关键字并打印多个关键字的关联行
【发布时间】:2018-08-31 18:16:57
【问题描述】:

我正在尝试搜索包含大量无关信息的 .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 将起作用,假设该行包含完全按照该顺序的单词。您是说要查找包含任何顺序的单词的行吗?
  • 另外,for l in data[i:i:3] 是怎么回事?为什么不只是print (line)
  • 其实我只是把它改成了打印线。不,我想搜索彼此独立的三个单词。为了提高透明度,我正在对医疗数据进行研究,并希望针对这些情况提取任何不同的因素。例如,如果患者的病情检测呈阳性,则有一个评分系统,所以我要搜索的其中一件事是该评分系统的名称并打印“患者有一个“在此处插入评分系统名称”分数of...",因为它是这样写在文件中的。
  • @JohnGordon 抱歉忘记给你加标签

标签: python text-extraction


【解决方案1】:

这是我用于解析文本的旧 python 脚本之一。

它使用了一点正则表达式,但应该能带你去你想去的地方。

#!/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

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

【讨论】:

    【解决方案2】:

    你可以替换你的:

    if searchPhrase1 in line:
    

    if any([x in line for x in ['your', 'search', 'phrases']]):
    

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

    【讨论】:

    • 对不起,也许我对编程还是太陌生,但我希望它返回该短语所在的行。这是作为布尔值返回还是如果它为真,它将打印该行
    • 它以布尔值形式返回。因此,如果为 True,它将继续执行 if 块内的下一行(应该是 print(line))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    相关资源
    最近更新 更多