【问题标题】:How can I search within a document for a keyword and then subsequent key words within a set number of lines of the original keyword in Python?如何在文档中搜索关键字,然后在 Python 中原始关键字的一组行内搜索后续关键字?
【发布时间】:2011-04-28 21:09:56
【问题描述】:

我想在文档中搜索一个关键字,然后检查该关键字是否在另一个关键字的 5 行之内。如果是,我想打印该行和后面的 50 行。

在这个例子中,我在文档中搜索“carrying”这个词,我想确保“carrying”这个词在“Financial Assets:”这个词的 5 行之内,我的代码能够找到并打印当我只包含搜索“carrying”时的行,但是当我包含搜索“Financial Assets:”时,它没有找到任何东西(即使我知道它在文档中)。

import urllib2

data = []

html = urllib2.urlopen("ftp://ftp.sec.gov/edgar/data/1001627/0000950116-97-001247.txt")
searchlines = html.readlines()
for m, line in enumerate(searchlines):
    line = line.lower()
    if "carrying" in line and "Financial Assets:" in searchlines[m-5:m+5]: 
        for l in searchlines[m-5:m+50]:
            data.append(l)
print ''.join(data)

任何帮助将不胜感激。

【问题讨论】:

    标签: python search


    【解决方案1】:

    而不是

    "Financial Assets:" in searchlines[m-5:m+5]
    

    你需要:

    any("Financial Assets:" in line2 for line2 in searchlines[m-5:m+5])
    

    您的原始代码会查找正好包含内容“Financial Assets:”的行,而不是在每行中将其作为子字符串查找。

    【讨论】:

      【解决方案2】:

      表达式

      "carrying" in line
      

      在行内的任何位置搜索字符串。然而声明

      "Finantial Assets:" in searchlines[m-5:m+5]
      

      正在该子列表中搜索完全匹配(即完全是“金融资产:”的行)。您需要将第二部分更改为类似

      "Finantial Assets:" in " ".join(searchlines[m-5:m+5])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-23
        • 1970-01-01
        相关资源
        最近更新 更多