I'm trying to create a function:
word_count("I do not like it Sam I Am")
gets back a dictionary like:
{'i': 2, 'do': 1, 'it': 1, 'sam': 1, 'like': 1, 'not': 1, 'am': 1}
I've no idea how to begin.
I'm trying to create a function:
word_count("I do not like it Sam I Am")
gets back a dictionary like:
{'i': 2, 'do': 1, 'it': 1, 'sam': 1, 'like': 1, 'not': 1, 'am': 1}
I've no idea how to begin.
def word_count(sentence):
d = sentence.lower().split()
d = {x: d.count(x) for x in d}
return d
Using pandas could work:
import pandas as pd
def word_count(string):
df = pd.DataFrame(string.split())
df['count'] = 1
grouped = df.groupby(by=0).agg({'count':'count'}).reset_index()
output = dict()
for idx, row in grouped.iterrows():
output[row[0]] = row['count']
return output
Output:
{'Am': 1, 'I': 2, 'Sam': 1, 'do': 1, 'it': 1, 'like': 1, 'not': 1}
Use collections.Counter
:
Counter(s.lower().split())
Output:
Counter({'am': 1, 'do': 1, 'i': 2, 'it': 1, 'like': 1, 'not': 1, 'sam': 1})