Python ValueError:解包的值太多(预期为 2 个)错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28222915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ValueError: too many values to unpack (expected 2) errors
提问by Ddude
My code:
我的代码:
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)
My Output:
我的输出:
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)
I am trying to accomplish making of a keywords glossary using a text file as storage. I keep running into this error which is causing the program to not work.
我正在尝试使用文本文件作为存储来完成关键字词汇表的制作。我一直遇到这个错误,导致程序无法运行。
My text file contents:
我的文本文件内容:
bug, this is a test
test, this is another test
testing,testing
123,12354
采纳答案by Jonathan
I think you want this:
我想你想要这个:
>>> line = "hello,world,foo,bar"
>>> (key, value) = line.split(",", 1)
>>> key
'hello'
>>> value
'world,foo,bar'
>>>
The change being: (key, value) = line.split(",", 1)
变化是: (key, value) = line.split(",", 1)
Passing 1 as the second argument to split tells split to stop after it comes across 1 comma, passing the rest of the line to value.
将 1 作为第二个参数传递给 split 告诉 split 在遇到 1 个逗号后停止,将行的其余部分传递给 value。
From the docs,
从文档中,
str.split([sep[, maxsplit]]) (...) If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements).
str.split([sep[, maxsplit]]) (...) 如果给定了 maxsplit,则最多完成 maxsplit 次分割(因此,列表最多有 maxsplit+1 个元素)。