我的代码:
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
答案 0 :(得分:6)
我想你想要这个:
>>> line = "hello,world,foo,bar"
>>> (key, value) = line.split(",", 1)
>>> key
'hello'
>>> value
'world,foo,bar'
>>>
更改为:(键,值)= line.split(“,”,1)
传递1作为split的第二个参数告诉split在遇到1个逗号后停止,将该行的其余部分传递给value。
来自docs,
str.split([sep [,maxsplit]]) (......) 如果给出maxsplit,则最多完成maxsplit拆分(因此,列表 最多只能有maxsplit + 1个元素。)