【问题标题】:Extract string with bibliographic data from a .txt file into a dictionary in python将带有书目数据的字符串从.txt文件中提取到python中的字典中
【发布时间】:2016-07-14 19:43:57
【问题描述】:

我想编写一个 python 函数,它从带有书目数据的文本文件中提取某些字符串元素。 该文件包含不同的行:

shakespeare, william: macbeth. novel, second edition, cambridge, 2005

每一行由\n分隔。

如何将这些行提取到如下结构中:

author : shakespeare, william
title : macbeth

usw.

【问题讨论】:

  • 你试过什么?对于与正则表达式相关的问题,我一直更喜欢使用像 regex101.com 这样的测试站点,并尝试使用我正在尝试处理的示例输入。实时结果有助于直观地了解它们的工作原理。
  • 这是我目前的代码:import re def meta_dict(): with open("bib.txt", "rt", encoding="utf-8") as infile, open("bib.json", "wt", encoding="utf-8") as outfile: content = infile.read() line = content.splitlines() for single in line: author = re.search (r'^[A-Z][a-z]+\s[A-Z][a-z]+|^[A-Z][a-ä]+,\s[A-Z][a-z]+|^[A-Z][a-ü]+|^[A-Z].[A-Z].\s[A-Z][a-z]+|^[A-Z][a-z]*\s[a-z]+|^[A-Z][a-z]+\s[a-z]+\s[A-Z][a-z]+', single) print (author)
  • 通过编辑将添加内容移动到问题正文中。它们在那种形式下是不可读的。

标签: regex python-3.x dictionary text-extraction


【解决方案1】:

你可以做这样的事情。然后每一行都有自己的字典。

d = {}
s = "shakespeare, william: macbeth. novel, second edition, cambridge, 2005"
data = s.split(".")[0].split(": ")
d["author"] = data[0]
d["title"] = data[1]

print d
#Output
{'title': 'macbeth', 'author': 'shakespeare, william'}

【讨论】:

  • 好的,到目前为止一切都很好,但是我怎样才能对每一行都这样做呢?我想要一个具有两个功能的模块。一个提取字符串,这是我用上面的代码计算出来的。第二个函数应该对每一行都这样做......
猜你喜欢
  • 2013-07-03
  • 1970-01-01
  • 2013-01-10
  • 1970-01-01
  • 2021-07-07
  • 2017-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多