python - Python 中的句子拆分并使其成为有序字典

标签 python

我想分割我的文本并将其存储以制作有序的字典

For example:

1.This is my text.
2.This is 2nd Text.

我想拆分数字和文本并将其存储在有序字典中,例如

Ordered Dict 

"1":"This is my text"
"2":"This is 2nd text"

我试过了。 split 但它对我不起作用。如何做到这一点?

d = OrderedDict()
text_data = [ "1.This is my text.","2.This is 2nd text"]
for i, f in enumerate(text_data):
id = f.split('.')
d[id] = text_data[i]
print(i, " :: ", id, " =>\n", d[id], "\n" + "*" * 100 + "\n")

我哪里出错了?制作 OrderedDict

最佳答案

你们很接近。按点分割字符串后,使用索引访问元素。

例如:

from collections import OrderedDict

d = OrderedDict()
text_data = [ "1.This is my text.","2.This is 2nd text"]
for i, f in enumerate(text_data):
    val = f.split('.')           #str.split
    d[val[0]] = val[1]           #Use Index. 

for k, v in d.items():
    print(k, v)

关于python - Python 中的句子拆分并使其成为有序字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52160520/

相关文章:

python - 为什么 s[len(s)-1 :-1:-1] not work?

python - 如何从python中的文件中删除除空格之外的特殊字符?

python - 从Pygame/PyOpenGL到iOS的最简单路径。

python - Matplotlib 简单的不同颜色线条图

python - GAE : How long to wait for eventual consistency?

python - 使用 matplotlib 增加饼图大小,radius 参数似乎什么都不做

python - 使用 python 启动使用 chcp 65001 预激活的控制台窗口

python - 我在运行 'sudo apt autoremove python' 时删除了数据库

python - 使用 html5 视频标签时视频无法在 safari 中播放

python - 将信号中继到包含的小部件