我如何从一个句子创建字典,使键是句子中的字母和字母的重新排列值

尽管我是python的新手,但我一直在尝试回答一个问题,该问题要求我使用标头def counter(input_string)编写代码,将小写和大写字母存储为字符串字母,然后创建一个键代表的字典句子中的每个唯一字母及其值代表带有count_letters单词的每个字母的出现次数。返回函数之后,我将使用counter(sentence)调用输出 码

def counter(input_string):
    alphabet='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    sentence = "Jim quickly realized that the beautiful gowns are expensive"
    count_letters = dict(letter in sentence,letter occurrence)
    return count_letters 

即使句子很长,代码也应该可以工作。   错误

File "<ipython-input-354-ea2f29797fba>", line 5
    count_letters = dict(letter in sentence,letter occurrence)
                                                   ^
SyntaxError: invalid syntax

有时当我没有错误时,它只会输出count_letters中写的内容

评论
宇智波~
宇智波~

这应该为您工作:

from collections import Counter

sentence = "Jim quickly realized that the beautiful gowns are expensive"
print(Counter(sentence))

Counter creates a dictionary that contains the frequencies of all items in the given collection.

点赞
评论