简体   繁体   中英

Read certain part of string from file

Trying python after a very long time now.

I have a file that has a line:

My_NUMBER                 =  24

I want to extract this number ( here I have assumed 24 but this is something I want to extract based on My_NUMBER.In my python code I am able to read the line

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

However this does print blank output and not the number. Can anyone commet in case I am doing anything obviously wrong here?

This is the perfect job for a regex:

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

I'd go with something like this

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

Might be better off using regex

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"

From here: 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

try something like this:

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
for line in lines:
    if line.startswith(' My_NUMBER                 ='):
        num = line.split('=')[-1].strip()
        print num
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]

Untested, but should work

The tidiest way, I would say, is to loop over each line, split based on = , then check if the value before the = is MY_NUMBER

The str.partition function is good for this (it's similar to split, but always returns 3 chunks). Also using str.strip means you don't need to worry about the whitespace

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM