Need to copy the contents of a text file to a dictionary

时间:2015-12-10 01:59:06

标签: python list file python-3.x dictionary

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

1 个答案:

答案 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

说明

  1. 使用with open('file_name.txt') as fobj:打开文件这将打开文件,并承诺在dedenting后关闭它。

  2. 制作一个新的空字典:synonyms = {}

  3. 浏览所有行for line in fobj:

  4. 用逗号分隔每一行,并从每个单词中删除多余的空格:[entry.strip() for entry in line.split(',')].

  5. 使用新的* - 方法在Python 3中解压缩迭代,以分割键和值key, *values =

  6. 将值添加到结果synonyms[key] = values

  7. 增加:

    打印字和随机同义词:

    import random
    
    for word, syns in synonyms.items():
        print(word, random.choice(syns))  
    

    打印:

    word1 synonym12
    word2 synonym22