Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 计算句子中字母的出现次数_Python - Fatal编程技术网

Python 计算句子中字母的出现次数

Python 计算句子中字母的出现次数,python,Python,如何从一个句子中创建一个字典,以便关键是字母计数字母在句子中出现的次数以及字母重复的次数 虽然我是python新手,但我一直在尝试回答一个问题,该问题要求我使用头def计数器(input_string),编写一个函数,将小写和大写字母存储为字符串字母表,然后创建一个字典,其中键表示句子中的每个唯一字母,值表示每个字母与单词计数字母的出现次数。在返回函数之后,我将使用计数器(语句)调用输出 这是我的密码 def counter(input_string): alphabet='abcdef

如何从一个句子中创建一个字典,以便关键是字母计数字母在句子中出现的次数以及字母重复的次数

虽然我是python新手,但我一直在尝试回答一个问题,该问题要求我使用头
def计数器(input_string)
,编写一个函数,将小写和大写字母存储为字符串字母表,然后创建一个字典,其中键表示句子中的每个唯一字母,值表示每个字母与单词计数字母的出现次数。在返回函数之后,我将使用
计数器(语句)
调用输出

这是我的密码

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
文件“”,第5行
计数字母=听写(句子中的字母,字母出现)
^
SyntaxError:无效语法

有时,当我没有错误时,它只输出以计数字母书写的内容。

这应该适用于您:

from collections import Counter

sentence = "Jim quickly realized that the beautiful gowns are expensive"
print(Counter(sentence))
创建包含给定集合中所有项的频率的词典

另一个选项是不使用
计数器

sentence = "Jim quickly realized that the beautiful gowns are expensive"
alphabet=list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
hits = dict([
    (alphabet[i], sentence.count(alphabet[i]))
    for i in range(len(alphabet))
    if sentence.count(alphabet[i])
])
print(hits)

那么,
字母出现
应该指什么?你只是随机地把这些词写在你的代码中间。也重复它为句子工作,但是当我试图用它来称呼另一个地址=长地址时,它没有。work@DavidAdewunmi什么是长的?那句话是什么?对不起,我又试了一次,它起了作用,这是我拒绝用的大写字母,关于Counter so@David Sthanks@DavidAdewunmi如果你能接受我的回答,我将不胜感激