-2

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.

khelwood
  • 55,782
  • 14
  • 81
  • 108

3 Answers3

2
def word_count(sentence):
  d = sentence.lower().split()
  d = {x: d.count(x) for x in d}
  return d
DSC
  • 1,153
  • 7
  • 21
0

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}

Sebastien D
  • 4,369
  • 4
  • 18
  • 46
0

Use collections.Counter:

Counter(s.lower().split())

Output:

Counter({'am': 1, 'do': 1, 'i': 2, 'it': 1, 'like': 1, 'not': 1, 'sam': 1})
Chris
  • 29,127
  • 3
  • 28
  • 51