Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Translator
#6
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 -------------------
Reply


Messages In This Thread
Translator - by Zatoichi - Feb-11-2018, 09:13 PM
RE: Translator - by Larz60+ - Feb-12-2018, 12:27 AM
RE: Translator - by Zatoichi - Feb-12-2018, 12:41 AM
RE: Translator - by Larz60+ - Feb-12-2018, 12:44 AM
RE: Translator - by Zatoichi - Feb-12-2018, 12:52 AM
RE: Translator - by Larz60+ - Feb-13-2018, 01:27 AM
RE: Translator - by Zatoichi - Feb-13-2018, 02:16 AM
RE: Translator - by Larz60+ - Feb-13-2018, 02:22 AM
RE: Translator - by Larz60+ - Feb-13-2018, 02:27 AM
RE: Translator - by Zatoichi - Feb-13-2018, 03:04 AM
RE: Translator - by Larz60+ - Feb-13-2018, 05:18 AM
RE: Translator - by Zatoichi - Feb-14-2018, 03:34 AM
RE: Translator - by Larz60+ - Feb-14-2018, 04:56 AM
RE: Translator - by Zatoichi - Feb-15-2018, 04:01 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] Alphabetic Telephone Number Translator teafshadow 4 5,141 Oct-20-2019, 02:56 PM
Last Post: perfringo
  Alphabetic Telephone Number Translator MEH012 4 22,206 Apr-25-2018, 08:47 PM
Last Post: woooee

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020