Feb-13-2018, 01:27 AM
You have to do it a bit differently if you want to accumulate:
counts = {} def add_sentence(sentence): slist = sentence.split() for word in slist: word = word.strip() if word in counts: counts[word] += 1 else: counts[word] = 1 def print_counts(): for key, value in counts.items(): print('{:<10} {:<10}'.format(key, value)) print('\n-------------------\n') def main(): sentence1 = 'This is a random sentence, if a random sentence is what you want' sentence2 = 'This is another sentence like the first' add_sentence(sentence1) print_counts() add_sentence(sentence2) print_counts() main()result:
Output:This 1
is 2
a 2
random 2
sentence, 1
if 1
sentence 1
what 1
you 1
want 1
-------------------
This 2
is 3
a 2
random 2
sentence, 1
if 1
sentence 2
what 1
you 1
want 1
another 1
like 1
the 1
first 1
-------------------