Skip to content Skip to sidebar Skip to footer

Counting Unique Words

Question: Devise an algorithm and write the Python code to count the number of unique words in a given passage. The paragraph may contain words with special characters such as !,

Solution 1:

You need to remove these 2 lines and add the line:

REMOVE:  
line.lower()   
l=line.split(" ")

ADD:
l = re.sub(r"\s+[\!\?\.\,\:\@]+\s+", r" ", s2.lower()).split(" ")

Solution 2:

Your problem is wrong iterating. Since set() returns unordered unique collection, you are iterating through unique list.

Instead of for word in d: try: for word in l:

edit: And change if word in count: into if word in count.keys():, because you want to check if key word exist.

Solution 3:

The problem with your code is that you didn't convert your input to lower case because the str.lower doesn't works in-place.So you need to change the following line :

line.lower()

to :

line = line.lower()

But as a more pythonic way you can split your sentence to get a list of words and strip them with punctuation then use collections.Counter to get a dictionary contains the words and those frequency.

from collections importCounter

line=raw_input().lower()

counter_object= Counter([i.strip('!?.,:;') for i in line.split()])

Post a Comment for "Counting Unique Words"