【问题标题】:Parsing blocks of text within a file into objects将文件中的文本块解析为对象
【发布时间】:2020-08-21 11:42:57
【问题描述】:

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

#*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 text-parsing


【解决方案1】:

您可以尝试使用 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'}]

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

【讨论】:

    猜你喜欢
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多