0

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")
  1. In the top_n_words function, I've declare that c is global. Should I declare it global in word_appears function? It doesn't work.
  2. Why I can't reference to the c in the print function? Does the order of the top_n_words, word_appears affect the final print function?
  3. What is a good practice to handle this kind of situation?
Community
  • 1
  • 1
Nick
  • 8,451
  • 13
  • 57
  • 106
  • I dont see the need to reference it. It is a global variable after if can be used anywhere. The best to do it would be is to create two separate local variables and play around with them in the function. – m0bi5 Nov 14 '15 at 12:11
  • What version are you using? – Rick Nov 14 '15 at 12:14
  • @RickTeachey I'm using python 3.3.5. – Nick Nov 14 '15 at 12:14

1 Answers1

1

Put all code in functions and use only arguments to make the counter available. For example:

from collections import Counter


def read_words(file_name):
    with open(file_name) as f:
        words = f.read().lower().split()
    return words


def top_n_words(counter, n):
    top_n = counter.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(counter, w):
    print("The word '{word:s}' appears {time:d} times.".format(word=w,
        time=counter[w]))


if __name__ == '__main__':

    def main(file_name):
        words = read_words(file_name)
        counter = Counter(words)
        top_n_words(counter, 12)
        print("-" * 20)
        print("Total words: %d" % len(words))
        word_appears(counter, "history")

    main('words.txt')
Mike Müller
  • 82,630
  • 20
  • 166
  • 161
  • `Put all code in functions and use only arguments to make the counter available` This makes things clear! Thank you for your kind to starters. – Nick Nov 14 '15 at 13:21