python - 读取文本文件(以冒号分隔的单词)并获取元组列表

标签 python

我有一个名为words.txt的文本文件,其中包含用冒号分隔的单词和描述对,例如:

word1:description 1 bla bla bla
word2:description 2 blah blah
...

我想要一个像这样的结构:

[('word1', 'description 1 bla'), ('word2', 'description 2 blah')]

如果您认为与元组列表不同的另一种结构更好,请告诉我...我很喜欢使用列表理解的解决方案,但我陷入了困境。

最佳答案

怎么样:

[line.split(':', 1) for line in open('words.txt')]

dict(line.split(':', 1) for line in open('words.txt'))

关于python - 读取文本文件(以冒号分隔的单词)并获取元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6380644/

相关文章:

python - 如何修改另一个python文件中的变量?

python - Numpy 高级索引 : same index used multiple times in +=

python - 通过 Python/SUDS 调用运行时 SOAP 方法

python - 在用于下载的 python 脚本中禁用 google chrome 上的病毒扫描

python - Python 脚本的 Crontab 每 5 分钟执行一次

python - Tensorflow 对象检测 API : Custom VGG 16 model

python - 在内存脚本上使用 2to3

python - 如何检查字符串是否包含子字符串的所有字符?

python - 使用 Pandas 提取HTML中的复选框值

python - Xpath没有给出结果scrapy python