从文件中读取字符串的某些部分

时间:2012-10-31 12:42:06

标签: python

现在很长一段时间后尝试python。

我有一个有一行的文件:

My_NUMBER                 =  24

我想提取这个数字(这里我假设24,但这是我想要基于My_NUMBER提取的东西。在我的python代码中我能够读取该行

with open(filename) as f: lines = f.read().splitlines()

for line in lines:
    if line.startswith(' My_NUMBER                 ='):
        line=(line.rsplit(' ', 1)[0])
        num= line.rsplit('=',1)[1].split("=")[0]
        num = num.strip(" ")
        print num

但是这会打印空白输出而不是数字。如果我在这里做任何明显错误的事情,有人可以通过吗?

7 个答案:

答案 0 :(得分:3)

这是正则表达式的完美工作:

import re
text = open(filename).read()
print re.search("^\s*My_NUMBER\s*=\s*(\d*)\s*$", text, re.MULTILINE).group(1)

答案 1 :(得分:2)

我选择这样的事情

with open(filename) as f:
    for line in f:
        line = line.replace(' ', '')
        if line.startswith('My_NUMBER'):
            number = line.partition('=')[2]
            print number

答案 2 :(得分:0)

最好使用正则表达式

import re

txt='My_NUMBER                 =  24'

re1='.*?'   # Non-greedy match on filler
re2='(\\d+)'    # Integer Number 1

rg = re.compile(re1+re2,re.IGNORECASE|re.DOTALL)
m = rg.search(txt)
if m:
    int1=m.group(1)
    print "("+int1+")"+"\n"

从这里: http://txt2re.com/index-python.php3?s=My_NUMBER%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20=%20%2024&4

答案 3 :(得分:0)

尝试这样的事情:

In [49]: with open("data1.txt") as f:
   ....:     for line in f:
   ....:         if line.strip():           #if line is not an empty line
   ....:             if "My_NUMBER" in line:
   ....:                 num=line.split("=")[-1] # split line at "=" and 
                                                 # return the last element
   ....:                 print num
   ....:                 
   ....:                 
  24

答案 4 :(得分:0)

for line in lines:
    if line.startswith(' My_NUMBER                 ='):
        num = line.split('=')[-1].strip()
        print num

答案 5 :(得分:0)

import re

exp = re.compile(r'My_NUMBER *= *(\d*)')
with open('infile.txt','r') as f:
    for line in f:
        a = exp.match(line)
        if a:
            print a.groups()[0]

未经测试,但应该有效

答案 6 :(得分:0)

我想说,最整洁的方法是循环遍历每一行,根据=进行拆分,然后检查=之前的值是MY_NUMBER

str.partition函数对此有用(它类似于split,但总是返回3个块)。同样使用str.strip意味着您不必担心空白

with open(filename) as f:
    lines = f.readlines()

for line in lines:
    key, eq, value = line.partition("=")
    if key.strip() == "MY_NUMBER":
        num = value.strip()
        print num