【问题标题】:Debugging IndexError: list index out of range调试 IndexError:列表索引超出范围
【发布时间】:2018-11-06 20:18:25
【问题描述】:

我是一名初级程序员。我知道

的意思
Index Error: list index out of range.

但我不明白这里有什么问题。

此代码在第 11 行工作/打印,然后自动停止。

如何调试?

数据集链接:https://github.com/YoeriNijs/TweetAnalyzer`

代码:

import nltk, random, csv, sys
from nltk.corpus import names
from nltk.tokenize import word_tokenize
import naiveBayesClassifier
import textblob


def selectTweets(row):
    #print row

    tweetWords = []
    words = row[0].split()
    for i in words:
        i = i.lower()
        i = i.strip('@#\'"?,.!')
        tweetWords.append(i)

#all_words = set(word.lower() for passage in tweetWords for word in word_tokenize(passage[0]))    
#print "******************************888"
#print tweetWords 
row[0] = tweetWords
print "******************************555"
t = [({word: (word in word_tokenize(x[0])) for word in tweetWords}, x[1]) for x in row]
print t


if counter <= 49:
    trainTweets.append(row)
    #print "******************************000"
    #print trainTweets

else:
    testTweets.append(row)

trainTweets = []
testTweets = []


  print "Tweet Sentiment Analyzer by Yoeri Nijs"
  print "*" * 30


 while True:

# Ask for filename
filename =  str(raw_input("> Please enter a filename (.csv): "))

#Check if filename ends with .csv
if filename.endswith(".csv"):

    try:

        #Open file
        with open(filename, 'rb') as csvfile: 
            reader = csv.reader(csvfile, delimiter=';', quotechar='|')

            #Print succes message
            print "> File opened successfully!"

            counter = 0
            for row in reader:
                selectTweets(row)
                counter += 1

            print "> Wait a sec for the results..."

            cl = naiveBayesClassifier.trainer(trainTweets)

    print("Accuracy of the classifier: {0}".format(cl.accuracy(testTweets)))
            cl.show_informative_features(10)
            cl.show_informative_features(10)

            while True:

                tweetWords = []
                tweet =  str(raw_input("Please enter the text of the tweet you want to analize: "))
                words = tweet.split()
                for i in words:
                    i = i.lower()
                    i = i.strip('@#\'"?,.!')
                    tweetWords.append(i)
                tweet = ' '.join(tweetWords)
                print "> Analyzing the tweet"

                # Classify some text
                print "Sentiment of the tweet:", (cl.classify(tweet))

                while True:
                    print
                    repeat =  str(raw_input("> Do you want to check another tweet (y/n)? "))

                    if repeat == "n":
                        print "Exit program"
                        sys.exit()
                    if repeat != "y":
                        print "Something went wrong"
                    if repeat == "y":
                        break         

    #If file does not exist, display this
    except IOError:
        print "File does not exist."

#Else if file does not end with .csv, do this
else:
    print "Please open a file that ends with .csv"

我将每个火车数据除以 ************************************555 以及为什么最后一个数据打印 'o'/' e'?? 此代码产生此错误:

> Please enter a filename (.csv): data.csv
> File opened successfully!
******************************555
""print like it 11 time then it stop......""
******************************555

[({'google': False, 'tron': False, 'i': True, 'theme': False, 'ics': False, 
 'hate': False}, 'hate'), ({'google': False, 'tron': False, 'i': False, 
 'theme': False, 'ics': False, 'hate': False}, 'e')]
******************************555



Traceback (most recent call last):
  File "C:\Users\Nahid\Downloads\Compressed\TweetAnalyzer-    
 master_2\TweetAnalyzer-master\script.py", line 68, in <module>
    selectTweets(row)
  File "C:\Users\Nahid\Downloads\Compressed\TweetAnalyzer-     
 master_2\TweetAnalyzer-master\script.py", line 29, in selectTweets
    t = [({word: (word in word_tokenize(x[0])) for word in tweetWords}, 
 x[1]) for x in row]
IndexError: list index out of range

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    通过快速查看,您以错误的模式打开了文件,二进制而不是文本。我已经运行代码没有任何错误,可能是我误解了问题。

    我承认,我不知道您为什么会收到超出范围的异常,我无法重新创建错误

    我所做的更改是:with open(filename, 'rt', encoding="utf8") as csvfile:

                                                  ^here
    

    我将模式更改为文本,并将编码更改为utf8,我认为无论如何它都会默认。

    Tweet Sentiment Analyzer by Yoeri Nijs
    ******************************
    > Please enter a filename (.csv): data.csv
    > File opened successfully!
    > Wait a sec for the results...
    Accuracy of the classifier: 0.772
    Most Informative Features
             contains(nexus) = True           positi : negati =     16.6 : 1.0
          contains(sandwich) = True           positi : negati =     14.6 : 1.0
               contains(ice) = True           positi : negati =     12.7 : 1.0
             contains(cream) = True           positi : negati =     12.7 : 1.0
             contains(looks) = True           positi : negati =      8.8 : 1.0
              contains(love) = True           positi : negati =      8.8 : 1.0
           contains(android) = True           positi : negati =      7.4 : 1.0
               contains(why) = True           negati : positi =      7.2 : 1.0
           contains(awesome) = True           positi : negati =      6.8 : 1.0
            contains(please) = True           negati : positi =      6.5 : 1.0
    Please enter the text of the tweet you want to analize: ice
    > Analyzing the tweet
    Sentiment of the tweet: positive
    > Do you want to check another tweet (y/n)? n
    Exit program
    

    错误抛出,(大量文本)

    【讨论】:

    • 非常感谢先生的回复。但它不断显示此错误,请问我能做些什么来提供帮助。
    • 请先生发送您的代码。 syedyunusnahid@gmail.com.我不知道我每次都遇到什么问题
    • 我现在没有,等我回家给你发。
    • 谢谢先生。非常感谢先生。这对我真的很有帮助,因为这是我的大学项目正在为这个项目挂起。先生您使用哪个版本 2.7/3.6。再次感谢先生的合作。
    • 已发送;)
    猜你喜欢
    • 2012-01-25
    • 2011-10-31
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多