2

I would like to load the contents of a .txt file as a string and extract a specific piece of information. The information, which has lots of text before and after it's occurence, looks like this:

ValueName:     1234

But could also look like:

ValueName:     123456

That is to say, the value is always a string of integers, but of varying length.

I would like to find the 'ValueName' in the string, and return characters starting 6 characters afterwards. My thought is to say check and see if the 10 characters starting 6 characters after the 'ValueName' are integers, and return them in order if they are. Is this possible? Thanks kindly.

2
  • Is the entire file comprised of key value pairs like the ones you used as an example? If that is the case you might want to look into reading the file into a dictionary which you can then easily query for values based on the key regardless of their length. If not a more broad sample of what is contained in the file would be useful.
    – JonathanV
    Jul 9, 2013 at 20:39
  • Is the other text ever on the same line as the Valuename: Value pairs, or are they always by themselves? Jul 9, 2013 at 20:45

7 Answers 7

3

You can use a regular expression to extract the value following ValueName:

>>> import re
>>> line = 'some dummy text ValueName:     123456 some dummy text'
>>> m = re.findall(r'ValueName:\s+([0-9]+)',line)
>>> m
['123456']

This will find multiple matches if they exist.

>>> import re
>>> line = 'blah blah ValueName: 1234 blah blah ValueName: 5678'
>>> m = re.findall(r'ValueName:\s+([0-9]+)',line)
>>> m
['1234', '5678']
3

Regular expressions will make this simpler, as Brian's answer (among others) shows.

But don't use a regex if you're not willing to understand what it does. If you want to put off the learning curve for now,* this isn't that hard to do with simple string processing:

def numeric_value_names(path):
    with open(path) as f:
        for line in f:
            bits = line.partition('ValueName:')
            if bits[1] and not bits[0]:
                rest = bits[2][6:].rstrip()
                if rest.isdigit():
                    yield rest

Using str.partition this way may be a bit obtuse to novices, so you may want to make the condition more obvious:

def numeric_value_names(path):
    with open(path) as f:
        for line in f:
            if line.startswith('ValueName:'):
                bits = line.partition('ValueName:')
                rest = bits[2][6:].rstrip()
                if rest.isdigit():
                    yield rest

* You definitely want to learn simple regular expressions at some point; the only question is whether you have something more pressing to do now…

2
  • @Brian: On the other hand, now is as good a time as any to learn regexps, and your answer shows how simple a regexp can be for a problem like this.
    – abarnert
    Jul 9, 2013 at 21:24
  • +1 for "But don't use a regex if you're not willing to understand what it does." I wish I could +2 for "* You definitely want to learn simple regular expressions at some point;".
    – 2rs2ts
    Jul 9, 2013 at 21:36
1
import re

regex = re.compile(r'ValueName:\s*([0-9]+)')
with open(file, "r") as f:
    for line in f:
        match = re.search(regex, line)
        if match:
            result = int(match.group(1))
            break
2
  • Why not just use finditer or findall instead of explicitly looping over match?
    – abarnert
    Jul 9, 2013 at 21:13
  • well you still need to check if the return value of findall is an empty list. Unless what you mean is to do findall for the whole file, which in my opinion is suboptimal because once you find the string you where looking for you can brake (this is what I understand from OP's specifications)
    – vfiskewl
    Jul 10, 2013 at 13:05
1

Use Regular Expressions

import re
for line in text
  re.search('^ValueName: (\d+)',line).group(1)

And if you need to sort them then you should put them on a list.

lst.append(re.search('^ValueName: (\d+)',line).group(1))

lastly just sort the list

sorted(lst)

Next I show you a complete example so you can extract what you need

import re

text = ['ValueName: 33413','ValueName: 443234531','ValueName: 5243222','ValueName: 33']
lst = []

for line in text:
  lst.append(re.search('^ValueName: (\d+)',line).group(1))

lst = [int(x) for x in lst]
for x in sorted(lst):
  print(x)
0
0

You could do something like this:

for line in open("file"):
    if "1234" in line:
    print line

Source: http://ubuntuforums.org/showthread.php?t=820319

2
  • He is parsing out values that could be different all the time. This searches specifically for '1234'
    – Brian
    Jul 9, 2013 at 20:48
  • So what? He could change that.
    – Rentsy
    Jul 10, 2013 at 20:39
-1

Using regular expression you could do something like

regex = re.compile("^(.*[0-9]{4,}.*)$")
for line in regex.findall(your_text_here):
    print line

Given regex

 ^(.*[0-9]{4,}.*)$

will match all lines that have atleast 4 integers somewhere in the middle.

0
-1

You could do this

import re

re.findall(r'ValueName:\d\d\d',s)

if 's' is your string variable (name) and \d is the number of integers you're looking for. In your case it would be \d\d\d\d\d\d...not totally pretty but it works.

1
  • This won't work. Try it on his example: re.findall(r'ValueName:\d\d\d', 'ValueName: 123456'). It not only doesn't handle the spaces, it also only reads the first 3 digits instead of all of them, and it also fails to check that the rest of the line is all digits.
    – abarnert
    Jul 9, 2013 at 21:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.