Reputation: 309
I have some code that I intend to print out all the unique words in a string that will be inputted by a user:
str1 = input("Please enter a sentence: ")
print("The words in that sentence are: ", str1.split())
unique = set(str1)
print("Here are the unique words in that sentence: ",unique)
I can get it to print out the unique letters, but not the unique words.
Upvotes: 3
Views: 25841
Reputation: 1
You can us this code:
str1 = input("Please enter a sentence: ")
print("The words in that sentence are: ", str1.split(' '))
str2=str1.split(' ')
unique = set(str2)
print("Here are the unique words in that sentence: ",unique)
Upvotes: 0
Reputation: 432
Another way of doing it:
user_input = input("Input: ").split(' ')
duplicates = []
for i in user_input:
if i not in duplicates:
duplicates.append(i)
print(duplicates)
Upvotes: 0
Reputation: 618
Also, you can use:
from collections import Counter
str1 = input("Please enter a sentence: ")
words = str1.split(' ')
c = Counter(words)
unique = [w for w in words if c[w] == 1]
print("Unique words: ", unique)
Upvotes: 0
Reputation: 787
String.split(' ')
takes a string and creates a list of elements divided by a space (' '
).
set(foo)
takes a collection foo and returns a set
collection of only the distinct elements in foo
.
What you want is this: unique_words = set(str1.split(' '))
The default value for the split separator is whitespace. I wanted to show that you can supply your own value to this method.
Upvotes: 10