I have a text file such that each line consists of one word followed by a comma-separated list of that word's synonyms. So for example, one line would look like this:
word, synonym1, synonym2, synonym3
so the first word in each line is the key and the rest are its values
答案 0 :(得分:2)
with open('file_name.txt') as fobj:
synonyms = {}
for line in fobj:
key, *values = [entry.strip() for entry in line.split(',')]
synonyms[key] = values
生成此词典synonyms
:
{'word1': ['synonym11', 'synonym12', 'synonym13'],
'word2': ['synonym21', 'synonym22', 'synonym23']}
此文件内容:
word1, synonym11, synonym12, synonym13
word2, synonym21, synonym22, synonym23
使用with open('file_name.txt') as fobj:
打开文件这将打开文件,并承诺在dedenting后关闭它。
制作一个新的空字典:synonyms = {}
。
浏览所有行for line in fobj:
。
用逗号分隔每一行,并从每个单词中删除多余的空格:[entry.strip() for entry in line.split(',')].
使用新的*
- 方法在Python 3中解压缩迭代,以分割键和值key, *values =
。
将值添加到结果synonyms[key] = values
。
打印字和随机同义词:
import random
for word, syns in synonyms.items():
print(word, random.choice(syns))
打印:
word1 synonym12
word2 synonym22