简体   繁体   English

将带有书目数据的字符串从.txt文件中提取到python中的字典中

[英]Extract string with bibliographic data from a .txt file into a dictionary in python

i want to code a python function, which extracts certain string elements out of a textfile with bibliographical data. 我想编写一个python函数,该函数从带有书目数据的文本文件中提取某些字符串元素。 The file contains different lines like that: 该文件包含如下不同的行:

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

Each line is been separated by a \\n . 每行用\\n分隔。

How can i extract these lines into a structure like: 我如何将这些行提取到类似的结构中:

author : shakespeare, william
title : macbeth

usw. usw。

You could do something like this. 你可以做这样的事情。 Every line would have its own dictionary then. 每一行都有自己的字典。

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'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM