python - 如何使用python从文本文件制作字典

标签 python dictionary distinct-values

我的文件看起来像这样:

aaien 12 13 39
aan 10
aanbad 12 13 14 57 58 38
aanbaden 12 13 14 57 58 38
aanbeden 12 13 14 57 58 38
aanbid  12 13 14 57 58 39
aanbidden 12 13 14 57 58 39
aanbidt 12 13 14 57 58 39
aanblik 27 28
aanbreken 39
...

我想制作一个字典,键 = 单词(如“aaien”),值应该是它旁边的数字列表。 所以它必须看起来像这样: {'aaien': ['12, 13, 39'], 'aan': ['10']}

这段代码似乎不起作用。

document = open('LIWC_words.txt', 'r')
liwcwords = document.read()
dictliwc = {}
for line in liwcwords:
    k, v = line.strip().split(' ')
    answer[k.strip()] = v.strip()

liwcwords.close()

python 给出了这个错误:

ValueError: need more than 1 value to unpack

最佳答案

您将行拆分为一个单词列表,但只给它一个键和值。

这会起作用:

with open('LIWC_words.txt', 'r') as document:
    answer = {}
    for line in document:
        line = line.split()
        if not line:  # empty line?
            continue
        answer[line[0]] = line[1:]

请注意,您不需要为 .split() 提供参数;如果没有参数,它会在空格处拆分并为您去除结果。这样您就不必显式调用 .strip()

另一种方法是仅在第一个空格处拆分:

with open('LIWC_words.txt', 'r') as document:
    answer = {}
    for line in document:
        if line.strip():  # non-empty line?
            key, value = line.split(None, 1)  # None means 'all whitespace', the default
            answer[key] = value.split()

.split() 的第二个参数限制了拆分的次数,保证最多返回 2 个元素,从而可以解压分配给 key 的值

任何一种方法都会导致:

{'aaien': ['12', '13', '39'],
 'aan': ['10'],
 'aanbad': ['12', '13', '14', '57', '58', '38'],
 'aanbaden': ['12', '13', '14', '57', '58', '38'],
 'aanbeden': ['12', '13', '14', '57', '58', '38'],
 'aanbid': ['12', '13', '14', '57', '58', '39'],
 'aanbidden': ['12', '13', '14', '57', '58', '39'],
 'aanbidt': ['12', '13', '14', '57', '58', '39'],
 'aanblik': ['27', '28'],
 'aanbreken': ['39']}

如果您仍然只看到一个 键和文件的其余部分作为(拆分)值,则您的输入文件可能使用了非标准的行分隔符。使用 universal line ending support 打开文件,通过将 U 字符添加到模式:

with open('LIWC_words.txt', 'rU') as document:

关于python - 如何使用python从文本文件制作字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14505898/

相关文章:

python - 如何将嵌套字典列表转换为 Pandas 数据框?

mysql - SQL - 选择不同的列而不排除行

python - OpenCV python 中的 estimateRigidTransform

python - 根据组绘制条形图

C# 数组或其他数据结构

python - 如何在 Python 中生成唯一随机 float 列表

c# - 如何独立获得每个属性的不同值

python - Django 模型表单 : Seeding a FK related field in the form

python - 从 S3 存储桶下载图像并将其存储在本地以外的变量中 (boto3)

python - 为什么 PyScripter 控制台中的输出不同?