开发者

Python Regex to Parse String and Return Tuple

I've been given some strings to work with. Each one represents a data set and consists of the data set's name and the associated statistics. They all have the following form:

s= "| 'TOMATOES_PICKED'                                  |       914 |       1397 |"

I'm trying to implement a function that will parse the string and return the name of the data set, the first number, and the second number. There are lots of these strings and each one has a different name and associated stats so I've figured the best way to do this is with regular expressions. Here's what I have so far:

def extract_data2(s):
    import re
    name=re.search('\'(.*?)\'',s).group(1)
    n1=re.search('\|(.*)\|',s)
    return(name,n1,)

So I've done a bit of reading on regular expressions and figured out how to return the name. For each of the strings that I'm working with, the name of the data set is bounded by ' ' so that's how I found the name. That part works fine. My problem is with getting the numbers. What I'm thinking right now is to try to match a pattern that is preceded by a vertical bar ('|'), then anything (which is why I used .*), and followed by another vertical bar to try to get the first number. Does anyone know how I can do this in Python? What I tried in the above code for the first number returns basically the whole string as my output, whereas I want to get just the number. -I am very new to programming so I apologize if this question seems rudimentary, but I have been reading and searching quite diligently for answers that are close to my case with no luck. I appreciate any help. The idea is that it will be able to:

return(name,n1,n2)

so that when the user inputs a string, it can just parse up the string and return the important information. I've noticed in my attempts to get the numbers so far that it will return the number as a string. Is there anyway to return n1 or n2 as just a number? Note that for some of the strings n1 an开发者_StackOverflow社区d n2 could be either integers or have a decimal.


I would use a single regular expression to match the entire line, with the parts I want in named groups ((?P<name>exampl*e)).

import re
def extract_data2(s):
    pattern = re.compile(r"""\|\s*                 # opening bar and whitespace
                             '(?P<name>.*?)'       # quoted name
                             \s*\|\s*(?P<n1>.*?)   # whitespace, next bar, n1
                             \s*\|\s*(?P<n2>.*?)   # whitespace, next bar, n2
                             \s*\|""", re.VERBOSE)
    match = pattern.match(s)

    name = match.group("name")
    n1 = float(match.group("n1"))
    n2 = float(match.group("n2"))

    return (name, n1, n2)

To convert n1 and n2 from strings to numbers, I use the float function. (If they were only integers, I would use the int function.)

I used the re.VERBOSE flag and raw multiline strings (r"""...""") to make the regex easier to read.


Using regex:

#! /usr/bin/env python

import re

tests = [
"| 'TOMATOES_PICKED'                                  |       914 |       1397 |",
"| 'TOMATOES_FLICKED'                                 |     32914 |       1123 |",
"| 'TOMATOES_RIGGED'                                  |        14 |       1343 |",
"| 'TOMATOES_PICKELED'                                |         4 |         23 |"]

def parse (s):
    mo = re.match ("\\|\s*'([^']*)'\s*\\|\s*(\d*)\s*\\|\s*(\d*)\s*\\|", s)
    if mo: return mo.groups ()

for test in tests: print parse (test)


Try using split.

s= "| 'TOMATOES_PICKED'                                  |       914 |       1397 |"
print map(lambda x:x.strip("' "),s.split('|'))[1:-1]
  • Split : transform your string into a list of string
  • lambda function : removes spaces and '
  • Selector : take only expected parts


Not sure that i have correctly understood you but try this:

import re

print re.findall(r'\b\w+\b', yourtext)


I would have to agree with the other posters that said use the split() method on your strings. If your given string is,

>> s = "| 'TOMATOES_PICKED'                          |       914 |       1397 |"

You just split the string and voila, you now have a list with the name in the second position, and the two values in the following entries, i.e.

>> s_new = s.split()
>> s_new
['|', "'TOMATOES_PICKED'", '|', '914', '|', '1397', '|']

Of course you do also have the "|" character but that seems to be consistent in your data set so it isn't a big problem to deal with. Just ignore them.


With pyparsing, you can have the parser create a dict-like structure for you, using the first column values as the keys, and the subsequent values as an array of values for that key:

>>> from pyparsing import *
>>> s = "| 'TOMATOES_PICKED'                                  |       914 |       1397 |"
>>> VERT = Suppress('|')
>>> title = quotedString.setParseAction(removeQuotes)
>>> integer = Word(nums).setParseAction(lambda tokens:int(tokens[0]))
>>> entry = Group(VERT + title + VERT + integer + VERT + integer + VERT)
>>> entries = Dict(OneOrMore(entry))
>>> data = entries.parseString(s)
>>> data.keys()
['TOMATOES_PICKED']
>>> data['TOMATOES_PICKED']
([914, 1397], {})
>>> data['TOMATOES_PICKED'].asList()
[914, 1397]
>>> data['TOMATOES_PICKED'][0]
914
>>> data['TOMATOES_PICKED'][1]
1397

This already comprehends multiple entries, so you can just pass it a single multiline string containing all of your data values, and a single keyed data structure will be built for you. (Processing this kind of pipe-delimited tabular data was one of the earliest applications I had for pyparsing.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜