Order a sentence alphabetically and count the number of times each words appears and print in a table
Posted
by
JaAnTr
on Stack Overflow
See other posts from Stack Overflow
or by JaAnTr
Published on 2013-10-25T09:34:02Z
Indexed on
2013/10/25
9:54 UTC
Read the original article
Hit count: 226
python
|python-2.7
I am struggling with the print in a table part of the question. So far I have managed to order the user inputted sentence alphabetically and count the number of times each word occurs. Here is the code:
thestring = (raw_input())
sentence = thestring.split(" ")
sentence.sort()
count = {}
for word in thestring.split():
try: count[word] += 1
except KeyError: count[word] = 1
print sentence
print count
And when I run the code I get this:
['apple', 'apple', 'banana', 'mango', 'orange', 'pear', 'pear', 'strawberry']
{'apple': 2, 'pear': 2, 'strawberry': 1, 'mango': 1, 'orange': 1, 'banana': 1}
However, ideally I want it printed in a table that looks something like:
apple.....|.....2
banana....|.....1
mango.....|.....1
orange....|.....1
pear......|.....2
strawberry|.....1
Thanks for any help!
© Stack Overflow or respective owner