[英]How do I print the first line of each paragraph of a text file in Python?
[英]How to make a dictionary in python from a text file seperated by paragraph with the key in the first line of each new paragraph?
我有一个包含以下信息的文本文件:
Cake 1
Cake description 1
Cake description 2
Cake description 3
Cake 2
Cake description (2) 1
Cake description (2) 2
Cake description (2) 3
Cake 3
Cake description (3) 1
Cake description (3) 2
我想知道如何在 python 中进行编码以将文本文件作为字典导入,键分别为 cake 1、cake 2、cake 3 和对应于蛋糕的值
IE
cake = { cake 1: ['cake description 1\n', 'cake description 2\n', 'cake description 3\n'],
cake 2: ['cake description 2(1)\n', 'cake description 2(2)\n', 'cake description 2(3)\n'],
cake 3: ['cake description 3(1)\n', 'cake description 3(2)\n'] }
谢谢!
您需要在\\n\\n
上拆分文本,然后单独拆分每个段落。
values = []
with open('youfile.txt','r') as f:
text = f.read()
for paragraph in text.split('\n\n'):
tmp = paragraph.split('\n',1)
key, value = tmp[0], tmp[1]
values.append({key: value})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.