用pyparsing解析名称

时间:2012-10-25 16:39:14

标签: python pyparsing

我有一个名字和年龄的文件,

john 25 
bob 30 
john bob 35

这是我到目前为止所拥有的

from pyparsing import *

data = '''
    john 25 
    bob 30 
    john bob 35
'''

name = Word(alphas + Optional(' ') + alphas)

rowData = Group(name +
                Suppress(White(" ")) +
                Word(nums))

table = ZeroOrMore(rowData)

print table.parseString(data)

我期待的输出是

[['john', 25], ['bob', 30], ['john bob', 35]]

这是stacktrace

Traceback (most recent call last):
  File "C:\Users\mccauley\Desktop\client.py", line 11, in <module>
    eventType = Word(alphas + Optional(' ') + alphas)
  File "C:\Python27\lib\site-packages\pyparsing.py", line 1657, in __init__
    self.name = _ustr(self)
  File "C:\Python27\lib\site-packages\pyparsing.py", line 122, in _ustr
    return str(obj)
  File "C:\Python27\lib\site-packages\pyparsing.py", line 1743, in __str__
    self.strRepr = "W:(%s)" % charsAsStr(self.initCharsOrig)
  File "C:\Python27\lib\site-packages\pyparsing.py", line 1735, in charsAsStr
    if len(s)>4:
TypeError: object of type 'And' has no len()

2 个答案:

答案 0 :(得分:3)

pyparsing会自动删除空格,以便您可以编写更清晰的语法。所以,你的名字解析器应该更像是:

# Parse for a name with an optional surname
# Note that pyparsing is built to accept "john doe" or "john        doe"
name = Word(alphas) + Optional(Word(alphas))

然后,行解析器:

# Parses a row of a name and an age
row = Group(name) + Word(nums)

但是,你会得到一个相当复杂的结构,每行([(['john', 'doe'], {}), '25'], {}),但我希望你能看到如何使用它。我建议不要使用pyparsing来解析整个字符串,但如果您的数据是基于行的,则迭代地逐行解析它。我认为事情变得更简单了:

for line in input_string.splitlines():
    results = row.parseString(line)
    # Do something with results...

答案 1 :(得分:0)

以下代码可以使用内置字符串库解决您的问题。

def main():
    f = open('filename.txt')
    fe = open('ERROR.TXT','w+')
    for line in f.readlines():
        # print line,
        lst = line.split()
        try:
            name = lst[0]
            age = lst[1]

        # process name and age valuse

        except IndexError as e:
            print e
            fe.write(e)
        except IOError as e:
            print e
            fe.write(e)

if __name__ == '__main__':
     main()