在文本框中拆分行时出现值错误

2024-10-03 09:17:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用“-”将文本文件中的每一行拆分为两行,但一直出现以下错误:

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

Tags: toindeflineanswersoptionssplitquestions
2条回答

问题是因为在输入文本(.txt)文件的第21行有多个-,但您只需要一个。你知道吗

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

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

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

当你做这样的赋值时,你隐含地假设a_list中包含了多少个值,这里是2。如果大于或小于2,那么如果不做一些非常令人惊讶和没有帮助的事情(比如让一个空的,或者让列表中的一些元素没有赋值),就没有好的方法来给出value1value2值。你知道吗

所以too many values to unpack意味着在文件中至少有一行line.split('-')会导致2个以上的元素,也就是说,至少有一行有多个-。你知道吗

相关问题 更多 >