Using variable 'criteria_names' before assignment pylint(E0601).
This error pops up only for the 'criteria_names' list which is already assigned, but not for the other lists, which are assigned the same way. Any pointers or solutions are very appreciated!
CODE SNIPPET:
data = list()
lines = list()
n_vectors = list()
vectors = list()
medium_vectors = list()
classnames = list()
classes_insert_lines = list()
vectors_raw = list()
criteria_names = list()
def DataGet(temp_pulse_file):
data[:] = []
n_vectors[:] = []
vectors[:] = []
medium_vectors[:] = []
classnames[:] = []
classes_insert_lines[:] = []
vectors_raw[:] = []
criteria_names[:] = [] #<- this is where the error pops up
with open(temp_pulse_file, "r", encoding='utf-8') as file:
lines = (file.read()).split("\n")
file.close()
n = -1
for i in range(len(lines)):
data.append(lines[i].split(","))
if data[i][0] == ">":
n += 1
classnames.append(data[i][1])
classes_insert_lines.append(i + 1)
n_vectors.append(0)
vectors_raw.append([])
vectors.append([])
elif data[i][0] == "#":
weights = data[i][1:]
elif data[i][0] == "$":
criteria_names = list(data[i][1:])
else:
n_vectors[n] += 1
vectors[n].append(data[i])
vectors_raw[n].append(lines[i])
n_elems = len(vectors[0][0])
classes = len(classnames)
for i in range(classes):
for j in range(n_vectors[i]):
for k in range(n_elems):
vectors[i][j][k] = float(vectors[i][j][k])
return n_elems, classes, n_vectors, weights, lines, classes_insert_lines, vectors_raw
n_elems, classes, n_vectors, weights, lines, classes_insert_lines, vectors_raw = DataGet(getcurrentdir() + 'db.pulse')
print(' criteria_names:',criteria_names)
When I remove criteria_names[:] = [], no errors whatsoever for the other lists used in the function. Anything helps.
Thanks to #martineau and #Barmar, added global criteria_names at the beginning of the DataGet() function and it worked like a miracle. Weird tho.
Related
I am new to Python, thus apologize in advance! I am trying to return two lists from a function with a while loop that reads an xml file. I can't figure out how to do it. I am referring to imres (integer) and subres (2 integers) in the code below, that are found ~10 times in the loop. Debuging shows that the variables are properly filled in the loop, but I don't know how to return the filled lists and I get the empty lists instead. Thanks.
def getresolution(node):
imres = []
subres = []
child4 = node.firstChild
while child4:
...
for child8 in keepElementNodes(child7.childNodes):
if child8.getAttribute('Hash:key') == 'ImageSize':
X = float(child8.getElementsByTagName('Size:width')[0].firstChild.data)
Y = float(child8.getElementsByTagName('Size:height')[0].firstChild.data)
imres += [[X, Y]]
if child8.getAttribute('Hash:key') == 'Resolution':
subres += [int(child8.firstChild.data)]
getresolution(child4)
child4 = child4.nextSibling
return [imres, subres]
[imres, subres] = getresolution(xml_file)
Not tested but this should point you in the right direction:
def getresolution(node):
imres = []
subres = []
child4 = node.firstChild
while child4:
...
for child8 in keepElementNodes(child7.childNodes):
if child8.getAttribute('Hash:key') == 'ImageSize':
X = float(child8.getElementsByTagName('Size:width')[0].firstChild.data)
Y = float(child8.getElementsByTagName('Size:height')[0].firstChild.data)
imres += [[X, Y]]
if child8.getAttribute('Hash:key') == 'Resolution':
subres += [int(child8.firstChild.data)]
t_imres, t_subres = getresolution(child4)
imres += t_imres
subres += t_subres
child4 = child4.nextSibling
return [imres, subres]
[imres, subres] = getresolution(xml_file)
def swiss_pairings(self):
players = self.player_standings()
players_paired = []
i = 0
// name = players.keys()[i]
match_player = 1
while match_player < range(len(players)):
// name_match_player = players.keys()[match_player]
player_one_id = Player.objects.get(name=name)
player_two_id = Player.objects.get(
name=name_match_player)
if self.has_played_before(player_one_id, player_two_id):
match_player += 1
else:
self.report_match(player_one_id, player_two_id)
players_paired.append(player_one_id.name, player_two_id.name)
del players[name]
del players[name_match_player]
break
return players_paired
The commented lines are producing that dictionaries are not indexed. What can be the replacement for those two lines?? I want only the "keys".
In the code below I get the following error:
"local variable 'moodsc' referenced before assignment"
I'm new to programming and python. I'm struggling with interpreting other questions on the similar topic. Any context around this specific code would be helpful.
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()
Ok #joshp, I think you need to globalise some variables, because the error is 'moodsc referenced before assignment', I think the code only gets as far as moodsc += txt[word] but you may also have trouble with pos and neg.
Try global moodsc and pos etc. before you define moodsc and pos etc. If this doesn't work try global moodsc before moodsc += txt[word] and so forth, you may need to use global in both places for it to work, I often find that this is needed in my code, to globalise it at definition and wherever else you use it (at the start of each function and statement where it is used).
def parse_actor_data(actor_data):
while 1:
line = actor_data.readline().strip()
if line.count('-') > 5:
break
actor_movie = {}
values = []
actor_name = ''
running_list = []
movie = []
for line in actor_data:
position = line.find(')')
running = line[:position + 1]
value = running.split('\t')
for k in value:
if k != '':
running_list.append(k)
actor_name_list = value[0].split(',')
actor_name = actor_name_list[0] + actor_name_list[-1]
for i in range(len(running_list)):
if value[0] == running_list[i]:
position2 = i
movie = running_list[position2+1:]
actor_movie[actor_name] = movie
check = actor_movie.keys()
for c in range(len(check)):
if len(check[c]) < 1:
actor_movie.pop(check[c])
return actor_movie
Problem I'm having now is that only the first item of movie is added into the actor_movie anyone can help? i tried so long for this already i seriously have no idea why isn't this working...
Every time you run:
actor_movie[actor_name] = movie
you're overwriting the last movie that was associated with that actor. Try something like this instead where you're storing a list of movies, not just a single value:
try:
actor_movie[actor_name].append(movie)
except KeyError:
actor_movie[actor_name] = [movie]
There are other ways (defaultdict, dict.setdefault, etc.) to do the same thing but that should get you up and running.
The following script is supposed to fetch a specific line number and parse it from a live website. It works for like 30 loops but then it seems like enumerate(f) stops working correctly... the "i" in the for loop seems to stop at line 130 instead of like 200 something. Could this be due to the website I'm trying to fetch data from or something else? Thanks!!
import sgmllib
class MyParser(sgmllib.SGMLParser):
"A simple parser class."
def parse(self, s):
"Parse the given string 's'."
self.feed(s)
self.close()
def __init__(self, verbose=0):
"Initialise an object, passing 'verbose' to the superclass."
sgmllib.SGMLParser.__init__(self, verbose)
self.divs = []
self.descriptions = []
self.inside_div_element = 0
def start_div(self, attributes):
"Process a hyperlink and its 'attributes'."
for name, value in attributes:
if name == "id":
self.divs.append(value)
self.inside_div_element = 1
def end_div(self):
"Record the end of a hyperlink."
self.inside_div_element = 0
def handle_data(self, data):
"Handle the textual 'data'."
if self.inside_div_element:
self.descriptions.append(data)
def get_div(self):
"Return the list of hyperlinks."
return self.divs
def get_descriptions(self, check):
"Return a list of descriptions."
if check == 1:
self.descriptions.pop(0)
return self.descriptions
def rm_descriptions(self):
"Remove all descriptions."
self.descriptions.pop()
import urllib
import linecache
import sgmllib
tempLine = ""
tempStr = " "
tempStr2 = ""
myparser = MyParser()
count = 0
user = ['']
oldUser = ['none']
oldoldUser = [' ']
array = [" ", 0]
index = 0
found = 0
k = 0
j = 0
posIndex = 0
a = 0
firstCheck = 0
fCheck = 0
while a < 1000:
print a
f = urllib.urlopen("SITE")
a = a+1
for i, line in enumerate(f):
if i == 187:
print i
tempLine = line
print line
myparser.parse(line)
if fCheck == 1:
result = oldUser[0] is oldUser[1]
u1 = oldUser[0]
u2 = oldUser[1]
tempStr = oldUser[1]
if u1 == u2:
result = 1
else:
result = user is oldUser
fCheck = 1
user = myparser.get_descriptions(firstCheck)
tempStr = user[0]
firstCheck = 1
if result:
array[index+1] = array[index+1] +0
else:
j = 0
for z in array:
k = j+2
tempStr2 = user[0]
if k < len(array) and tempStr2 == array[k]:
array[j+3] = array[j+3] + 1
index = j+2
found = 1
break
j = j+1
if found == 0:
array.append(tempStr)
array.append(0)
oldUser = user
found = 0
print array
elif i > 200:
print "HERE"
break
print array
f.close()
Perhaps the number of lines on that web page are fewer than you think? What does this give you?:
print max(i for i, _ in enumerate(urllib.urlopen("SITE")))
Aside: Your indentation is stuffed after the while a < 1000: line. Excessive empty lines and one-letter names don't assist the understanding of your code.
enumerate is not broken. Instead of such speculation, inspect your data. Suggestion: replace
for i, line in enumerate(f):
by
lines = list(f)
print "=== a=%d linecount=%d === % (a, len(lines))
for i, line in enumerate(lines):
print " a=%d i=%d line=%r" % (a, i, line)
Examine the output carefully.