【问题标题】:Why are my attempts to read content from txt file into dictionary failing?为什么我尝试将 txt 文件中的内容读入字典失败?
【发布时间】:2020-11-11 14:21:44
【问题描述】:

正如标题所示,我正在尝试用 Python 将文件读入字典。我得到的错误是“没有足够的值来解包(预期 2,得到 1)”。我浏览了不同的帖子,但出现了相同的错误,但建议的解决方案对我不起作用。 我的文本文件格式如下:

яблоко:the round fruit of a tree of the rose family, which typically has thin red or green skin and crisp flesh. Many varieties have been developed as dessert or cooking fruit or for making cider
банан:a long curved fruit which grows in clusters and has soft pulpy flesh and yellow skin when ripe
вишня:a small, round stone fruit that is typically bright or dark red

所以这个(改编自我在其他帖子上找到的答案)应该可以工作:

myDict = {}
with open("fruits.txt", "r") as file:
    for line in file:
        key, value = line.strip().split(":")
        myDict[key] = value
print(myDict)

但它抛出了上述错误。关于为什么的任何想法?

非常感谢您的阅读。

【问题讨论】:

  • 您的文件中可能有一行没有“:”来分隔它。它可能是一个空行。您可以使用try ... except ValueError 让您跳过坏行。

标签: python file dictionary


【解决方案1】:

将此作为对我评论的跟进。很可能您的文件中有没有分隔符的行。你可以跳过这样的坏行

try:
    key, value = line.strip().split(":")
    myDict[key] = value
except ValueError:
    continue  # will just go to the next item in the loop

【讨论】:

    【解决方案2】:

    尝试添加encoding 来打开函数。这段代码对我有用:

    myDict = {}
    with open("fruits.txt", encoding='utf8') as file:
        for line in file:
            key, value = line.strip().split(":")
            myDict[key] = value
    print(myDict)
    

    【讨论】:

    • 所以我尝试了 Cfreak 的回答,它解决了我所问的问题,但这解决了我在将西里尔文的文件内容打印到控制台后不久发现的问题,所以也谢谢你!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 2017-11-28
    相关资源
    最近更新 更多