python - 如何在 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'] }
谢谢!
解决方案
您需要拆分文本\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})
推荐阅读
- angular - 无法在 Angular 中重新格式化日期变量
- laravel - 图像像公共文件夹中的 tmp 文件一样保存
- c# - 将 .NET Core 项目编译为 .exe 文件而不是 .dll 文件
- gunicorn - WebSocket 连接失败:WebSocket 握手期间出错:意外响应代码:200
- javascript - 如何动态更新 div 以添加嵌入的推文,然后是其他 HTML 元素
- r - 在R闪亮中更新ActionButton单击事件的绘图输出
- python-3.x - 如何将 Excel 工作表中的 numpy 浮点数组乘以常数?
- c# - 从后台进程打开窗口并在 WPF 中从用户那里获取输入
- php - 如何在引导程序 4 的同一 PHP 页面中设置重置密码模式和显示配置文件模式
- opengl - 如何在不复制到 CPU 内存的情况下将 ffmpeg 纹理转换为 Open GL 纹理