简体   繁体   English

为什么我尝试将 txt 文件中的内容读入字典失败?

[英]Why are my attempts to read content from txt file into dictionary failing?

As the title suggests, I'm trying to read a file into a dictionary in Python.正如标题所暗示的,我正在尝试用 Python 将文件读入字典。 The error I'm getting is "not enough values to unpack (expected 2, got 1)".我得到的错误是“没有足够的值来解包(预期为 2,得到 1)”。 I've gone through different posts with the same error but the suggested solutions haven't been working for me.我浏览了不同的帖子,但出现相同的错误,但建议的解决方案对我不起作用。 My text file is formatted like:我的文本文件格式如下:

яблоко: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

So this (adapted from answers I found on other posts) should work:所以这(改编自我在其他帖子中找到的答案)应该有效:

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

But it's throwing the aformentioned error.但它抛出了上述错误。 Any ideas as to why?关于为什么的任何想法?

Thank you very much for reading.非常感谢您的阅读。

Putting this in an answer as a follow up to my comment.将此作为我的评论的后续回答。 Very likely you have lines in your file that don't have the separator.很可能您的文件中有没有分隔符的行。 You can skip the bad lines like this你可以跳过这样的坏行

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

Try to add an encoding to open function.尝试添加encoding以打开函数。 This code worked for me:这段代码对我有用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM