【问题标题】: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?python - 如何从以段落分隔的文本文件中使用每个新段落的第一行中的键在python中制作字典?
【发布时间】:2020-08-25 09:44:38
【问题描述】:

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

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 中编写代码以将文本文件作为字典导入 键是蛋糕1,蛋糕2,蛋糕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'] }

谢谢!

【问题讨论】:

  • 你尝试了什么?

标签: python list dictionary text-files


【解决方案1】:

您需要在\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})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多