我一直在尝试使用pyparsing模块进行一些操作,以便对常规解析有所了解。
我收到了一个面试问题(已提交,因此我认为现在没有任何道德问题)来处理类似于文本文件中的数据结构,类似于下面的数据结构。
Collection Top_Level_Collection "Junk1"
{
Column Date_time_column 1 {"01-21-2011"}
Collection Pig_Entry "Sammy"
{
Column Animal_locations 35 {"Australia", "England", "U.S."}
Data 4
{
4 0 72033 Teeth 2 {1 "2", 1 "3"};
1 0 36331 Teeth 2 {2 "2", 3 "4"};
2 3 52535 Teeth 2 {6 "4", 9 "3"};
4 0 62838 Teeth 2 {3 "7", 7 "6"};
}
}
}
我可以使用正则表达式和计数列来获取真正的hacky解决方案,以提取数据片段并将其组合在一起,但是我想扩展我的解析知识,以更有才华的方式做事。
可以看出,基本结构首先是“主要抽象数据类型”,然后是可选的“具体数据类型”,然后是“名称”或“条目数”,同时可以无限嵌套。
这是到目前为止我尝试解析成字典的结果:
import numpy as np
import pyparsing as pp
test_str = '''
Collection Top_Level_Collection "Junk"
{
Column Date_time_column 1 {"01-21-2011"}
Collection Pig_Entry "Sammy"
{
Column Animal_locations 35 {"Australia", "England", "U.S."}
Data 4
{
4 0 72033 Teeth 2 {1 "2", 1 "3"};
1 0 36331 Teeth 2 {2 "2", 3 "4"};
2 3 52535 Teeth 2 {6 "4", 9 "3"};
4 0 62838 Teeth 2 {3 "7", 7 "6"};
}
}
}
'''
if __name__ == '__main__':
expr = pp.Forward()
object_type = pp.Word( pp.alphanums + '_')
object_ident = pp.Word( pp.alphanums + '_')
object_name_or_data_num = pp.Word( pp.alphanums + '_".')
ident_group = pp.Group(object_type + pp.Optional(object_ident) + object_name_or_data_num)
nestedItems = pp.nestedExpr("{", "}")
expr << pp.Dict(ident_group + nestedItems)
all_data_dict = (expr).parseString(test_str).asDict()
print all_data_dict
print all_data_dict.keys()
返回:
{'Column': (['Date_time_column', '1', (['"01-21-2011"'], {}), 'Collection', 'Pig_Entry', '"Sammy"', (['Column', 'Animal_locations', '35', (['"Australia"', ',', '"England"', ',', '"U.S."'], {}), 'Data', '4', (['4', '0', '72033', 'Teeth', '2', (['1', '"2"', ',', '1', '"3"'], {}), ';', '1', '0', '36331', 'Teeth', '2', (['2', '"2"', ',', '3', '"4"'], {}), ';', '2', '3', '52535', 'Teeth', '2', (['6', '"4"', ',', '9', '"3"'], {}), ';', '4', '0', '62838', 'Teeth', '2', (['3', '"7"', ',', '7', '"6"'], {}), ';'], {})], {})], {}), 'Collection': (['Top_Level_Collection', '"Junk"'], {})}
['Column', 'Collection']
但是,我希望它返回的内容可以轻松发送到python中的类以创建对象。
我最好的猜测是将它们放在一个嵌套的字典中,键是2或3种对象类型的元组,值是一个字典,其下每个键值。即类似于以下内容:
{ (Collection, Top_Level_Collection, "Junk1"):
{ (Column, Date_time_column): ["01-21-2011"],
(Collection, Pig_Entry, "Sammy"):
{ (Column, Animal_locations): ["Australia", "England", "U.S."],
(Data): [[ 4 0 72033 {(Teeth):[1 "2", 1 "3"]} ]
[ 1 0 36331 {(Teeth):[2 "2", 3 "4"]} ]
[ 2 3 52535 {(Teeth):[6 "4", 9 "3"]} ]
[ 4 0 62838 {(Teeth):[3 "7", 7 "6"]} ]]
}
}
}
最佳答案
您将必须为数据创建类,然后对解析器使用“ setParseAction”,以便可以创建所需的任何数据结构。有关示例,请查看下面的简单示例:
#!/usr/bin/env python
from pyparsing import *
test_str="Alpha 1\nBeta 2\nCharlie 3"
aStmt = Word(alphas)("name") + Word(nums)("age")
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def myParse(t):
return Person(t.name, t.age)
aStmt.setParseAction(myParse)
for aline in test_str.split('\n'):
print aline
print aStmt.parseString(aline)
关于python - 从文本字符串解析数据对象结构,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24567393/