2

我有一份姓名和年龄的档案,

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]]

这是堆栈跟踪

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()
4

2 回答 2

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...
于 2012-10-25T16:56:57.357 回答
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()
于 2012-10-25T17:17:55.640 回答