如何解决将文件中的文本块解析为对象
我有一个文本文件,如下所示:(块用空行分隔)
#*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'}]
要创建一个对象,需要使用类并将字典值分配给类属性。但是,如果目标是处理数据,则字典列表应该足够好。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。