赋值前引用的局部变量“moodsc”

2024-10-01 15:33:45 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,我得到以下错误:

“赋值前引用了局部变量'moodsc'”

我不熟悉编程和python。我正在努力解释类似主题的其他问题。任何关于这个特定代码的上下文都会很有帮助。在

import re
import json
import sys

def moodScore(sent, myTweets):

  scores = {} # initialize an empty dictionary
  new_mdsc = {} # intitalize an empty dictionary
  txt = {}

  for line in sent:
    term, score  = line.split("\t")  # The file is tab-delimited. "\t" means "tab character"
    scores[term] = int(score)  # Convert the score to an integer.

  data = [] # initialize an empty list

  for line in myTweets:
    tweet = json.loads(line)
    if "text" in tweet and "lang" in tweet and tweet["lang"] == "en":
      clean = re.compile("\W+")
      clean_txt = clean.sub(" ", tweet["text"]).strip()
      line = clean_txt.lower().split()  

  moodsc = 0
  pos = 0
  neg = 0
  count = 1

  for word in range(0, len(line)):
    if line[word] in scores:
       txt[word] = int(scores[line[word]])
    else: 
       txt[word] = int(0)
    moodsc += txt[word]
    print txt 

    if any(v > 0 for v in txt.values()): 
      pos = 1 
    if any(v < 0 for v in txt.values()): 
      neg = 1 

    for word in range(0, len(line)): # score each word in line
      if line[word] not in scores:
        if str(line[word]) in new_mdsc.keys():
          moodsc2 = new_mdsc[str(line[word])][0] + moodsc
          pos2 = new_mdsc[str(line[word])][1] + pos
          neg2 = new_mdsc[str(line[word])][2] + neg
          count2 = new_mdsc[str(line[word])][3] + count
          new_mdsc[str(line[word])] = [moodsc2, pos2, neg2, count2]
        else:
          new_mdsc[str(line[word])] = [moodsc, pos, neg, count] 

def new_dict():
  for val in new_mdsc.values():
    comp = val[0] / val[3]
    val.append(comp)

  for key, val in new_mdsc.items():
    print (key, val[4])

def main():
    sent_file = open(sys.argv[1])
    tweet_file = open(sys.argv[2])
    moodScore(sent_file, tweet_file)
#    new_dict()

if __name__ == '__main__':
    main()

Tags: intxtnewforiflinevaltweet
1条回答
网友
1楼 · 发布于 2024-10-01 15:33:45

好的@joshp,我认为您需要全局化一些变量,因为错误是'moodsc referenced before assignment',我认为代码只能到达moodsc += txt[word],但是您可能在{}和{}上遇到问题。在

在定义global moodscpos之前,请尝试global moodsc和{}等。如果这不起作用,请在moodsc += txt[word]之前尝试global moodsc,以此类推,您可能需要在这两个地方使用global才能使其工作,我经常发现在我的代码中需要这样做,在定义和任何其他地方使用它(在每个函数和语句的开始处)使用它。在

相关问题 更多 >

    热门问题