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

问题描述

我有一个文本文件,如下所示:(块用空行分隔)

#*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的对象中。

预先感谢

解决方法

您可以尝试使用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.',#   'year': '2015'}]

要创建一个对象,需要使用类并将字典值分配给类属性。但是,如果目标是处理数据,则字典列表应该足够好。