繁体   English   中英

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

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

正如标题所暗示的,我正在尝试用 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:
    key, value = line.strip().split(":")
    myDict[key] = value
except ValueError:
    continue  # will just go to the next item in the loop

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

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