簡體   English   中英

Python:獲取/掃描某個字符串后的所有文本

[英]Python: Get/Scan All Text After a Certain String

我有一個使用 readlines() 讀取的文本文件。 我需要在文本文件中的關鍵字之后開始提取數據。 例如,在下面的關鍵字Hello World ,我想從Blah=100檢索值Blah=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

必須有一個簡單的方法來做到這一點。 請幫忙。 謝謝。

有很多方法可以做到。 這是一個:

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

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

這是一種方法,不一定是最好的; 我在這里對文本進行了硬編碼,但您可以使用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

正則表達式示例。

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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM