Python程序:计算字符串中的字符频率

创新互联Python教程:

创新互联于2013年成立,是专业互联网技术服务公司,拥有项目成都网站制作、成都做网站网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元南山做网站,已为上家服务,为南山各地企业和个人服务,联系电话:13518219792

编写一个 Python 程序,使用 for 循环和字典来计算字符串中的字符频率。在这个 Python 示例中,for 循环迭代整个字符串。我们把所有的字符数分配给字典键。

# Count Charcaters Frequency in a String

string = input("Please enter the Your Own String = ")
chardict = {}

for num in string:
    keys = chardict.keys()
    if num in keys:
        chardict[num] += 1
    else:
        chardict[num] = 1

print(chardict)

这个 Python 程序使用 Counter 集合对给定字符串中的所有字符频率进行计数。

# Count Charcaters Frequency in a String

from collections import Counter

string = input("Please enter the Your Own String = ")

chars = Counter(string)

print("Total Characters Frequency in this String = ")
print(chars)
Please enter the Your Own String = hello python programmers
Total Characters Frequency in this String = 
Counter({'o': 3, 'r': 3, 'h': 2, 'e': 2, 'l': 2, ' ': 2, 'p': 2, 'm': 2, 'y': 1, 't': 1, 'n': 1, 'g': 1, 'a': 1, 's': 1})

网站栏目:Python程序:计算字符串中的字符频率
新闻来源:http://www.hantingmc.com/qtweb/news8/149808.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联