将文件中的文本块解析为对象

2024-10-01 11:40:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个如下的文本文件:(块之间用一条空行分隔)

#*Approximate Distance Oracles with Improved Query Time.
#@Christian Wulff-Nilsen
#t2015
#cEncyclopedia of Algorithms
#index555036b37cea80f954149ffc

#*Subset Sum Algorithm for Bin Packing.
#@Julián Mestre
#t2015
#cEncyclopedia of Algorithms
#index555036b37cea80f954149ffd

我想解析每个块并将结果存储到一个名为Document的对象中

提前谢谢


Tags: oftimewithquerydistance文本文件algorithmsimproved
1条回答
网友
1楼 · 发布于 2024-10-01 11:40:05

您可以尝试使用python TTP库在字典列表中对其进行转换:

from ttp import ttp

data = """
#*Approximate Distance Oracles with Improved Query Time.
#@Christian Wulff-Nilsen
#t2015
#cEncyclopedia of Algorithms
#index555036b37cea80f954149ffc

#*Subset Sum Algorithm for Bin Packing.
#@Julián Mestre
#t2015
#cEncyclopedia of Algorithms
#index555036b37cea80f954149ffd
"""

template = """
#*{{ info | ORPHRASE }}
#@{{ author | ORPHRASE }}
#t{{ year }}
#c{{ title | ORPHRASE }}
#index{{ index }}
"""

parser = ttp(data, template)
parser.parse()
res = parser.result(structure="flat_list")
pprint.pprint(res)

# prints:
# [{'author': 'Christian Wulff-Nilsen',
#   'index': '555036b37cea80f954149ffc',
#   'info': 'Approximate Distance Oracles with Improved Query Time.',
#   'title': 'Encyclopedia of Algorithms',
#   'year': '2015'},
#  {'author': 'Julián Mestre',
#   'index': '555036b37cea80f954149ffd',
#   'info': 'Subset Sum Algorithm for Bin Packing.',
#   'title': 'Encyclopedia of Algorithms',
#   'year': '2015'}]

要创建对象,需要使用类并为类属性指定字典值。然而,如果目标是处理数据,字典列表应该足够好了

相关问题 更多 >