Python 如何避免解包元组时出现ValueError?
我有一个元组列表,如下所示:Python 如何避免解包元组时出现ValueError?,python,list,tuples,Python,List,Tuples,我有一个元组列表,如下所示: ('"FoxNews"', '"BREAKING: Federal appeals court rules against Trump administration on DACA"', 'tbd') ('"BREAKING: Federal appeals court rules against Trump administration on DACA"', 'tbd') 我正在尝试运行以下代码: Scored_NS = [] for (username, w
('"FoxNews"', '"BREAKING: Federal appeals court rules against Trump administration on DACA"', 'tbd')
('"BREAKING: Federal appeals court rules against Trump administration on DACA"', 'tbd')
我正在尝试运行以下代码:
Scored_NS = []
for (username, words, sentiment) in News_Sample:
... if type(words) is list:
... username =username
... words_scored = [t.lower() for t in words if len(t) >= 3]
... sentiment = classifier.classify(extract_features(words))
... else:
... username = username
... words_scored = [t.lower() for t in words.split() if len(t) >= 3]
... sentiment = classifier.classify(extract_features(words.split()))
... Scored_NS.append((username, words_scored, sentiment))
但是,我遇到了以下错误:
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
ValueError:没有足够的值来解包(预期为3,实际为2)
这是我正在寻找的输出:
('"FoxNews"', '"BREAKING: Federal appeals court rules against Trump administration on DACA"', 'neg')
基本上,代码将“tbd”替换为“pos”或“neg”标记,用于我正在进行的情绪分析。知道为什么会这样吗?我不确定我做错了什么,因为以下代码:
test_sample = []
for (words, sentiment) in test_tweets:
if type(words) is list:
words_filtered = [t.lower() for t in words if len(t) >= 3]
sentiment = classifier.classify(extract_features(words))
else:
words_filtered = [t.lower() for t in words.split() if len(t) >= 3]
sentiment = classifier.classify(extract_features(words.split()))
test_sample.append((words_filtered, sentiment))
当元组如下所示时工作:
('"FoxNews"', '"BREAKING: Federal appeals court rules against Trump administration on DACA"', 'tbd')
('"BREAKING: Federal appeals court rules against Trump administration on DACA"', 'tbd')
给出以下输出:
('"BREAKING: Federal appeals court rules against Trump administration on DACA"', 'neg')
以下是新闻\u示例
的示例:
[('"FoxNews"', '"BREAKING: Federal appeals court rules against Trump administration on DACA"', 'tbd'), ('"FoxNews"', '"Breaking News: Grand jury indicts captain of Missouri duck boat that sank in severe weather, killing 17 people"', 'tbd'), ('"FoxNews"', '"JUST IN: Police identify gunman who opened fire inside California bar, killing 12"', 'tbd'), ('"FoxNews"', '"JUST IN: Supreme Court Justice Ruth Bader Ginsburg fractures 3 ribs in fall"', 'tbd')]
我很确定在
News\u Sample
中有一个或多个大小为2的元组。我的建议是遍历该列表,如果列表中只有两个元素,就停止。该消息:Traceback(最近一次调用last):文件“”,第1行,在ValueError中:没有足够的值来解包(预期为3,得到2)
正是这样说的。News\u Sample
未定义。你需要做一个决定。我们不能给出一个明确的答案,直到你这样做,但@Yacine可能是正确的。同样值得注意的是,-块的是不相关的。您不妨将其替换为pass
。只是一个观察:words\u scored=[t.lower for t in words.split(),如果len(t)>=3]
第4行和第7行都将其作为t.lower而不是t.lower(),News\u Sample
中的一些元组只包含两个值,你知道这是为什么吗?你想如何处理它们?@martineau谢谢你的观察。问题是“News_Sample”的第一行是我的标题,只有两个值。我删除了它,代码运行良好。