2012-07-19 68 views
0

我有一個使用readlines()讀取的文本文件。我需要在文本文件中的關鍵字之後開始提取數據。例如,鍵字下面的Hello World之後,我想從布拉赫檢索值100 = 100:Python:獲取/掃描某個字符串後的所有文本

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

我可以很容易地取回了從文本文件所需的信息,但我需要它開始檢索僅在文本文件中的某個關鍵字之後,比如在上面的「Hello World」之後。我目前正在做的是使用.split('=')檢索值。因此,我將檢索Blah = 0,Blah = 2和Blah = 100的所有3個值。我只希望檢索文本文件中關鍵字後面的值,比如說'Hello World',這個值是Blah = 100。

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

+2

這通常只是閱讀文本和尋找關鍵字,然後尋找你想要的值。你試過什麼了? – PTBNL 2012-07-19 03:04:24

+0

我已閱讀使用readlines的文本,並獲得我想要的值。然而,這些值是在'Blah ='後使用.split('=')獲得的。因此,正如你所看到的,在關鍵字'hello world'之前,我還將檢索不需要的blah = 0和blah = 2。我只希望檢索文本文件中關鍵字後的值。 – 2012-07-19 03:06:08

+0

您應該查看行,並且如果當前行中有關鍵字,則應該搜索檢索值。有任何問題嗎? – ForEveR 2012-07-19 03:11:05

回答

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" 
+0

是的,我有你的想法。很明顯。一旦該行命中關鍵字,那麼我們將一個變量設置爲TRUE,隨後可以繼續執行我們的值檢索。感謝您的想法! – 2012-07-19 03:32:31

0

這裏有一個稍微僞codish答案 - 你只需要一旦你找到了關鍵字改變到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 
0

這裏有一種方法,不一定是最好的;我硬編碼的文字在這裏,但你可以使用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 
0

例如使用正則表達式。

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