首页 > 解决方案 > 如何在 python 中使用每个新段落的第一行中的键从按段落分隔的文本文件中制作字典?

问题描述

我有一个包含以下信息的文本文件:

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以及分别对应于蛋糕的值,

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

谢谢!

标签: pythonlistdictionarytext-files

解决方案


您需要拆分文本\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})

推荐阅读