1

很长一段时间后尝试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

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

4

7 回答 7

3

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

import re
text = open(filename).read()
print re.search("^\s*My_NUMBER\s*=\s*(\d*)\s*$", text, re.MULTILINE).group(1)
于 2012-10-31T12:45:54.673 回答
2

我会选择这样的东西

with open(filename) as f:
    for line in f:
        line = line.replace(' ', '')
        if line.startswith('My_NUMBER'):
            number = line.partition('=')[2]
            print number
于 2012-10-31T12:46:16.733 回答
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

于 2012-10-31T12:44:39.033 回答
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
于 2012-10-31T12:44:51.243 回答
0
for line in lines:
    if line.startswith(' My_NUMBER                 ='):
        num = line.split('=')[-1].strip()
        print num
于 2012-10-31T12:46:00.110 回答
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]

未经测试,但应该可以工作

于 2012-10-31T12:46:47.030 回答
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
于 2012-10-31T12:55:18.877 回答