Splitting Input Lines for Question-Answer Pairs
When splitting a line of input into multiple variables, you may encounter a ValueError indicating a need for more or fewer values to unpack. This issue arises when the line being split does not contain the delimiter character used in the split method.
Specifically, in the provided code, each line in the input file is split at the colon (:). If a line contains no colon or multiple colons, the split method will fail.
Causes of Value Errors
Solution
To resolve this issue, you can check whether the input line contains the expected number of values before splitting:
with open('qanda.txt', 'r') as questions_file: for line in questions_file: line = line.strip() if ':' in line: questions, answers = line.split(':') questions_list.append(questions) answers_list.append(answers)
This check ensures that the line contains a colon before attempting to split it. If the line does not contain a colon, it is ignored, preventing the ValueError from being raised.
以上是分割問答對的輸入行時如何處理 ValueError?的詳細內容。更多資訊請關注PHP中文網其他相關文章!