2012-07-19 69 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')