繁体   English   中英

ValueError:太多值无法解压缩(预期2个)错误

[英]ValueError: too many values to unpack (expected 2) errors

我的代码:

def dictest():
    global my_glossary
    # read all lines of the file
    inFile = open("glossary.txt", "r")
    inText = inFile.read()
    inFile.close()

    my_glossary = {}
    # iterate through all lines, after removing the line-end character(s)
    for line in inText.splitlines():
        if line != '':           # ignore empty lines
            (key,value) = line.split(",")
            my_glossary[key] = value

    addToGlossary = entryNew.get()
    addToGlossaryDef = outputNew.get()

    my_glossary[addToGlossary] = addToGlossaryDef

    # list all the dictionary entries
    for k,v in my_glossary.items():
        print('key:', k, ', value:', v)

我的输出:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
return self.func(*args)
File "I:\School\Working Glossary.py", line 59, in MultiFunc
dictest()
File "I:\School\Working Glossary.py", line 14, in dictest
(key,value) = line.split(",")
ValueError: too many values to unpack (expected 2)

我正在尝试使用文本文件作为存储来完成关键字词汇表的制作。 我不断遇到此错误,导致该程序无法正常工作。

我的文本文件内容:

bug, this is a test
test, this is another test
testing,testing
123,12354

我想你想要这个:

>>> line = "hello,world,foo,bar"
>>> (key, value) = line.split(",", 1)
>>> key
'hello'
>>> value
'world,foo,bar'
>>>

更改为:(键,值)= line.split(“,”,1)

将split作为第二个参数传递1告诉split在遇到1个逗号后停止,将行的其余部分传递给value。

文档中

str.split([sep [,maxsplit]])(...)如果指定了maxsplit,则最多完成maxsplit分割(因此,列表中最多包含maxsplit + 1个元素)。

暂无
暂无

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

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