Reputation: 57
Python counts every character, but not word. Something to do to change? Not using count()
dict = {}
def convert(sentence):
return (sentence.split())
sentece = input("write something: ")
print( convert(sentence))
for item in sentence:
if item not in ordbok:
dict[item] = 0
dict[item] += 1
print(dict)
Upvotes: 0
Views: 245
Reputation: 6466
Please find below the issues with your current logic:
iterate on the return list you get after convert(sentence).
if you iterate on the sentence, it will take character count
Please find the code below with the corrections:
dict = {}
def convert(sentence):
return (sentence.split())
sentence = input("write something: ")
print(convert(sentence))
for item in convert(sentence):
if item not in dict:
dict[item] = 0
dict[item] += 1
print(dict)
Upvotes: 1
Reputation: 24049
You can use collections.Counter
like below:
from collections import Counter
Counter(convert(sentence))
Your Whole code:
def convert(sentence):
return (sentence.split())
sentece = input("write something: ")
from collections import Counter
dct = Counter(convert(sentence))
Output:
write something: victorialangoe victorialangoe
Counter({'victorialangoe': 2})
Upvotes: 1
Reputation: 10699
You can easily count anything with collections.Counter.
from collections import Counter
word_count = Counter(sentence.casefold().split())
Here, word_count
would be a dictionary containing all words in the sentence
and their respective counts.
Upvotes: 2