python计算字符串中特定字符串出现个数_计算Python字符串中出现的字符数

有几种不同的方法,大多数是在jonrsharpe的评论中暗示的,但是我建议使用一个简单的^{}。在

set方法以及其他一些方法如下:# An approach using a set

def countwords_set(s):

for c in set(s):

if c == ' ': continue

print(c, 'in', s.count(c))

# An approach using a standard dict

def countwords_dict(s):

d = dict()

for c in s:

if c == ' ': continue # Skip spaces

d[c] = d.get(c,0) + 1 # Use the .get method in case the

# key isn't set

for c,x in d.items(): # Display results

print(c, 'in', x)

# An approach using a defaultdict (from the collections module)

def countwords_ddict(s):

from collections import defaultdict # Typically, imports go at the top

d = defaultdict(int)

for c in s:

if c == ' ': continue

d[c] += 1

for c,x in d.items():

print(c, 'in', x)

# An approach using a Counter (from the collections module)

def countwords_counter(s):

from collections import Counter # Typically, imports go at the top

counter = Counter(s)

# Counters can be accessed like dicts

for c,x in counter.items():

if c == ' ': continue

print(c, 'in', x)

# User input and comparison

s = str(input("Enter a paragraph "))

s = s.lower()

countwords_set(s)

print(" -")

countwords_dict(s)

print(" -")

countwords_ddict(s)

print(" -")

countwords_counter(s)

print(" -")

对于每种方法,输出基本上是相同的,尽管字符的顺序可能不同,因为Python字典是无序的。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值