我有名字和年齡的文件,解析名稱與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]]
這裏是堆棧跟蹤
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()
我認爲你故意選擇'pyparsing'作爲學習練習嗎?使用內置的字符串函數甚至是正則表達式對於那些微不足道的東西更好 –
@JonClements實際上這是一個很大的項目的一部分,我相信pyparsing比正則表達式更合適,我真的只需要知道如何做單一空間的事情。 – John