I've got headache with the global variable reference problem in a simple word frequency count program. I check the the answers from here and here, and the python docs; however, I still haven't got the idea of global variable reference.
from collections import Counter
with open('c:/Users/Nick/Downloads/sample_file.txt') as f:
words = f.read().lower().split()
c = Counter(words)
total_words = sum(c.values())
def top_n_words(n):
global c
# c = Counter(words)
top_n = c.most_common(n)
print("Top %d words are:" % n)
print("-" * 20)
for w, c in top_n:
# print("%10s: %-10s" % (w, c))
print("{word:>10s}: {counts:<10d}".format(word=w, counts=c))
def word_appears(w):
# global c
c = Counter(words)
print("The word '{word:s}' appears {time:d} times.".format(word = w, time = c[w]))
top_n_words(12)
print("-" * 20)
print("Total words: %d" % total_words)
print("Total words: {t:d}".format(t=sum(c.values())))
word_appears("history")
- In the
top_n_words
function, I've declare thatc
is global. Should I declare it global inword_appears
function? It doesn't work. - Why I can't reference to the
c
in theprint
function? Does the order of thetop_n_words
,word_appears
affect the final print function? - What is a good practice to handle this kind of situation?