【问题标题】:Python: Get/Scan All Text After a Certain StringPython:获取/扫描某个字符串后的所有文本
【发布时间】:2012-07-19 03:01:13
【问题描述】:

我有一个使用 readlines() 读取的文本文件。我需要在文本文件中的关键字之后开始提取数据。比如下面的关键字Hello World之后,我想从Blah=100中检索值100:

Blah=0 
Blah=2
Hello World
All the Text
 Will be Scan
And Relevant       
  Info will be
 Retrieved Blah=100

我可以轻松地从文本文件中检索我想要的信息,但我需要它仅在文本文件中的某个关键字之后开始检索,例如在上面的 'Hello World' 之后。我目前正在做的是使用.split('=') 检索值。因此,我将检索所有 3 个值,它们是 Blah=0Blah=2Blah=100。我只希望检索文本文件中某个关键字后面的值,比如'Hello World',即值Blah=100

必须有一个简单的方法来做到这一点。请帮忙。谢谢。

【问题讨论】:

  • 这通常只是阅读文本并寻找关键字,然后寻找您想要的值。到目前为止,您尝试过什么?
  • 我已经使用 readlines 阅读了文本并获得了我想要的值。但是,这些值是在 'Blah=' 之后使用 .split('=') 获得的。因此,如您所见,在关键字“hello world”之前,我还将检索不需要的 blah=0 和 blah=2。我只希望在文本文件中的关键字之后检索值。
  • 您应该查看行,如果当前行中有关键字,则应该搜索检索值。有什么问题吗?
  • 描述你想要什么,展示你在代码中做了什么,询问为什么你所做的事情违背了你的期望。

标签: python text keyword text-extraction


【解决方案1】:

有很多方法可以做到这一点。这是一个:

STARTER = "Hello World"
FILENAME = "data.txt"
TARGET = "Blah="

with open(FILENAME) as f:
    value = None
    start_seen = False
    for line in f:
        if line.strip() == STARTER:
            start_seen = True
            continue

        if TARGET in line and start_seen:
            _,value = line.split('=')
            break

if value is not None:
    print "Got value %d" % int(value)
else:
    print "Nothing found"

【讨论】:

  • 是的,我明白了你的想法。很明显。一旦该行命中关键字,我们就将一个变量设置为 TRUE,随后的行我们就可以继续进行值的检索。感谢您的想法!
【解决方案2】:

这是一个略带伪代码的答案 - 一旦找到关键字,您只需要一个更改为 True 的标志:

thefile = open('yourfile.txt')

key = "Hello World"
key_found = False

for line in thefile:
    if key_found:
        get_value(line)
        # Optional: turn off key_found once you've found the value
        # key_found = False
    elif line.startswith(key):
        key_found = True

【讨论】:

    【解决方案3】:

    这是一种方法,不一定是最好的;我在这里对文本进行了硬编码,但您可以使用file.read() 来获得类似的结果:

    the_text = '''Blah=0 
    Blah=2
    Hello World
    All the Text
     Will be Scan
    And Relevant       
      Info will be
     Retrieved Blah=100
    '''
    
    keyword = 'Hello World'
    
    lines = the_text.split('\n')
    for line_num, line in enumerate(lines):
        if line.find(keyword) != -1:
            lines = lines[line_num:]
            break
    
    the_value = None
    value_key = 'Blah'
    for line in lines:
        if line.find(value_key) != -1:
            the_value = line.split('=',2)[1]
            break
    
    if the_value:
        print the_value
    

    【讨论】:

      【解决方案4】:

      正则表达式示例。

      reg = re.compile("Hello World")
      data_re = re.ompile("Blah=(?P<value>\d)")
      with open(f_name) as f:
         need_search = False
         for l in f:
             if reg.search(l) is not None:
                need_search = True
             if need_search == True:
                res = data_re.search(l)
                if res is not None:
                   print res.groups('value')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-30
        • 2022-11-27
        • 1970-01-01
        相关资源
        最近更新 更多