我收到一个我不理解的ValueError



我被卡住了,不明白为什么我的代码不能工作。有人能帮我吗?我收到一个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)的行时,代码就工作了。所以我可以打印wordlist_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

这意味着'Malin'不在您的列表中,这就是您得到异常的原因。

即:

x = ['a', 'b']
x.index('c')

ValueError:"c"不在列表中

您可以在try/except块中处理此异常,或者理解单词不在列表中的原因

关于索引方法的文档

此方法返回找到的对象的索引,否则引发指示找不到值的异常。

我怀疑是因为

word = word.lower()

所以"马林"不在你的名单上,但"马林"在。假设它在那里。

相关内容

最新更新