2017-02-22 2 views
-2

Я пишу анализ настроений в кино, и в коде я получаю одну ошибку, а именно: invalid literal для int() с базой 10. Код читает отдельный текстовый файл, содержащий обзоры фильмов с его оценкой. ex) 4 Этот фильм был замечательный. Спасибо за помощь! Edit: ошибка появляется здесь: строка 38 баллов = INT (lineSplits [0] .strip())Что означает неверный литерал для int() с базой 10?

import re 
class WordStatistic: 
    def __init__(self, keyword, averageScore = 0, occurences = 0): 
     self.keyword = keyword 
     self.averageScore = averageScore 
     self.occurences = occurences 

    def getWord(self) : 
     return self.keyword 

    def getAverageScore(self) : 
     return self.averageScore 

    def getOccurences(self) : 
     return self.occurences 

    def addNewScore(self, newScore) : 
     oldScoreSum = self.averageScore * self.occurences 
     self.occurences = self.occurences + 1 
     self.averageScore = (oldScoreSum + newScore)/(self.occurences) 

    def printWordStatistic(self) : 
      print ("Word   : ", self.keyword) 
      print ("Occurences : ", self.occurences) 
      print ("Average Score : ", self.occurences, "\n\n") 
# "teaching" the code 
wordDictionary = {} 
fileInstance = open("movieReviews.txt",'r') 
fileText = fileInstance.read() 

# formatting and splitting 
reviewSplits = fileText.split("movieReviews") 
for review in reviewSplits : 
     review = review.strip() 
     if review == "" : 
      continue 
     lineSplits = review.split("\n") 
     score = int(lineSplits[0].strip()) 
     for i in range(1, len(lineSplits)) : 
      wordSplits = re.split("\t| ", lineSplits[i]) 
      for word in wordSplits : 
       if word == "" : 
        continue 
       # If it is already present, then update the score and count 
       # Otherwise just add the new entry to the dictionary 
       if wordDictionary in(word) : 
        wordStatistic = wordDictionary.get(word) 
        wordStatistic.addNewScore(score) 
       else : 
        wordStatistic = WordStatistic(word, score, 1) 
        wordDictionary[word] = wordStatistic 
# print the stats of the words 
def printAllWordStatistic(wordDictionary) : 
    for wordStatistic in wordDictionary.values() : 
     wordStatistic.printWordStatistic() 
# rating the actual review 
def calculateAverageOfReview(review) : 
    review.replace("\t", " ") 
    review.replace("\n", " ") 
    wordSplits = review.split(" ") 
    averageScore = 0.0 
    totalCount = 0; 
    for word in wordSplits : 
     if wordDictionary in (word) : 
      averageScore += wordDictionary.get(word).getAverageScore() 
      totalCount = totalCount + 1 
    if totalCount != 0 : 
     return averageScore/totalCount 
    return -1 
# getting user input and append multi lines of case of multi line review 
while (True) : 
    print ("\nEnter a review : "); 
    multiLines = [] 
    while True: 
     line = input() 
     if line: 
      multiLines.append(line) 
     else: 
      break 
    inputReview = '\n'.join(multiLines) 
    averageScore = calculateAverageOfReview(inputReview) 
    if averageScore != -1 : 
     if averageScore >= 2.50 : 
      print ("Positive Review"); 
     else : 
      print ("Negative Review"); 
    else : 
     print ("Unable to rate the review"); 
    if input("\nDo you want to continue ? (Y/N) : ") != "Y" : 
     print ("Quitting the session."); 
     exit() 
+2

Это означает, что один из символов в строке не находится в '1234567890. + -'. т.е. символ появляется в строке, которая не появляется в арифметике базы 10. –

+0

Это очень много кода для вопроса с одним предложением. –

+1

Возможно, вы можете уменьшить проблему до одной или двух строк. Сделайте это сейчас, а затем представите свой [MCVE]. –

ответ

1

Это означает, что int не знает, что делать с символами, которые не являются 0-9. Если у вас есть произвольная строка, которую вы хотите, чтобы вытащить несколько из, вы могли бы использовать регулярное выражение, так что вместо того, чтобы:

score = int(lineSplits[0].strip()) 

Что-то вроде

score = int(re.search('[0-9]+', lineSplits[0]).group())) 

, который будет захватывать первую группу цифр.

Смежные вопросы