python - 字母计数功能
问题描述
我需要定义一个函数,该函数接受一个字符串并计算输入中字母的数量(仅小写),例如,如果我输入“jack”,它将返回:
a=1,b=0,c=1,d=0,...,j=1,k=1,...,z=0.
所以我实现了以下内容:
def l_count(str):
str.lower()
for ch in str:
return str.count('a')
它只返回字符串中“a”的数量。由于我不想为所有字母表都这样做,所以我考虑过实现这样的列表理解:
al = [chr(i) for i in range(ord('a'),ord('z'))]
def l_count(str):
str.lower()
for character in str:
return str.count(al)
但我得到一个错误:
must be str, not list
我不知道如何更改它,因为我得到了同样的错误。
解决方案
这是一种使用方法collections.Counter
:
from collections import Counter
from string import ascii_lowercase
x = 'jack'
c = Counter(dict.fromkeys(ascii_lowercase, 0))
c.update(Counter(x))
print(*(f'{k}={v}' for k, v in c.items()), sep=',')
a=1,b=0,c=1,d=0,e=0,f=0,g=0,h=0,i=0,j=1,k=1,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0
您可能希望为lowercase
您的字符串添加逻辑,排除标点符号等。
推荐阅读
- vba - VBA检查范围内的单元格是否为红色然后退出子
- mysql - 如果至少包含此文本,则更新字段值
- java - 跨类/方法模拟 Java 对象
- python - 在视图中调用 REST 端点?
- python - 如何使用 pyspark 将 bz2 文件读入数据帧?
- ios - 是否可以使用 iOS12 发送 NFC APDU 命令
- css - 字体粗细覆盖我的自定义字体(wkhtmltopdf)
- linux - arch linux 上的 asp.net core 2.1 无法运行
- vba - Excel VBA 转到文件夹并将所有 Excel 文档另存为单独的 PDF 文件
- linux - cgroups v2 不支持 elasticsearch 2.2.x