我被困住了,不明白为什么我的代码不起作用。有人可以帮我吗?我收到一个ValueError说'Malin' is not in the list
。
for line in text_file:
clean_line = line.translate(None, ',.:;"-_')
list_of_a_line = clean_line.split()
#print list_of_a_line
#How do do I remove both quotation marks?
for word in list_of_a_line:
word = word.lower()
for one_focus_word in focus_words:
if word.lower() == one_focus_word.lower():
sentiment_point = 0
print word
index_number = list_of_a_line.index(word)
print index_number
当我阻止说
print list_of_a_line.index(word)
的行时,代码起作用。这样我就可以打印word
并且可以打印list_of_a_line
(请参见下面打印的列表)["internet", "IPS", "IPSs", "cobb", "comcast", "centrylink", "paris", "malin" ,"trump"]
随时对我的代码提出其他意见。
最佳答案
你做:
for word in list_of_a_line:
word = word.lower()
然后在此循环中:
index_number = list_of_a_line.index(word)
这意味着您在列表中查找单词的小写版本,而不是它包含的原始版本。这会引起值错误。
您可以使用
enumerate
来获取单词的索引,而无需使用.index()
:for index_number, word in enumerate(list_of_a_line):
for one_focus_word in focus_words:
if word.lower() == one_focus_word.lower():
sentiment_point = 0
print word
print index_number
关于python - 我收到一个我不理解的ValueError,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36655993/