在文本文件中分割行时的ValueError

时间:2017-12-28 20:53:03

标签: python string parsing

我想将文本文件的每一行拆分为两个" - ",但我一直收到这个错误:

File "quiz.py", line 21, in Vocab
    questions, answers = line.split("-")
    ValueError: too many values to unpack (expected 2)

我对编码很新,可以使用一些帮助。欢迎所有提示!

import hashlib

testFile = ""
def qSearch():
    options = input ("Vocab/Grammar/or Special? (v/g/s)")
    if options == "v":
        testFile = "Vocabtest"
        Vocab()
    elif options == "g":
        Grammar()
        testFile = "Grammartest"
    elif options == "s":
        Special()
        testFile = "Specialtest"
    else:
        qSearch()

def Vocab():
        with open('Vocabtest.txt','r') as f:
            for line in f:
                questions, answers = line.split("-") ### error
                print (questions)

qSearch()

我的文本文件中的文字格式如下:

Magandang umaga - Good Morning

Magandang hapon - Good Afternoon

Magandang gabi - Good evening

Magandang umaga sa’yo - Good Morning to you

Magandang hapon din sa’yo - Good Afternoon to you to

2 个答案:

答案 0 :(得分:1)

问题是因为在输入文本(.txt)文件的第21行,您有多个-,但您只需要一个。{/ p>

更安全的方法是只拆分一次:

questions, answers = line.split("-", 1)

答案 1 :(得分:1)

“解包”是您写作时所做的事情的名称 value1, value2 = a_list

当你做这样的任务时,你隐含地假设a_list中包含多少个值 - 这里是2.如果有多于或少于2,那么就没有好办法给出value1value2值并没有做出非常令人惊讶和无益的事情(比如留空,或者保留列表中的某些元素未分配)。

所以too many values to unpack表示文件中至少有一行line.split('-')会产生超过2个元素 - 也就是说,至少有一行包含多个-

相关问题