尝试创建字数统计功能

时间:2019-06-12 00:29:57

标签: python dictionary packing

我正在尝试创建一个函数:

word_count("I do not like it Sam I Am")

找回像这样的字典

{'i': 2, 'do': 1, 'it': 1, 'sam': 1, 'like': 1, 'not': 1, 'am': 1}

我不知道如何开始。

4 个答案:

答案 0 :(得分:2)

def word_count(sentence):
  d = sentence.lower().split()
  d = {x: d.count(x) for x in d}
  return d

答案 1 :(得分:0)

下面的功能应该起作用:

def word_count(string):
    """ This function counts words in a string"""

    word_dict = {}

    s = string.split()

    for word in s:
        if word not in word_dict:
            word_dict[word] = 1
        else:
            word_dict[word] += 1

    return word_dict

word_count("I do not like it Sam I Am")

返回:

{'I': 2, 'do': 1, 'not': 1, 'like': 1, 'it': 1, 'Sam': 1, 'Am': 1}

答案 2 :(得分:0)

使用熊猫可以工作:

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

输出:

  

{'Am':1,'I':2,'Sam':1,'do':1,'it':1,'like':1,'not':1}

答案 3 :(得分:0)

使用collections.Counter

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

输出:

Counter({'am': 1, 'do': 1, 'i': 2, 'it': 1, 'like': 1, 'not': 1, 'sam': 1})