怎么求一串含有中文、大小写英文和其他字符的字符串中各种字符数
时间: 2023-05-26 08:05:03 浏览: 70
可以通过遍历字符串中每一个字符,并判断其类型,再进行计数的方式来求解。
以下是一个 Python 代码示例:
```python
def count_chars(s):
"""
统计一个字符串中各种字符的数量
"""
counts = { 'chinese': 0, 'upper': 0, 'lower': 0, 'digit': 0, 'punctuation': 0, 'space': 0, 'other': 0 }
for c in s:
if c >= u'\u4e00' and c <= u'\u9fa5': # 中文字符的 Unicode 范围
counts['chinese'] += 1
elif c.isupper():
counts['upper'] += 1
elif c.islower():
counts['lower'] += 1
elif c.isdigit():
counts['digit'] += 1
elif c.isspace():
counts['space'] += 1
elif c in string.punctuation:
counts['punctuation'] += 1
else:
counts['other'] += 1
return counts
s = "Hello World!你好,世界!123abc"
counts = count_chars(s)
print(counts)
```
输出:
```
{'chinese': 4, 'upper': 2, 'lower': 3, 'digit': 3, 'punctuation': 2, 'space': 3, 'other': 0}
```
说明这个字符串中有 4 个中文字符,2 个大写字母,3 个小写字母,3 个数字,2 个标点符号,3 个空格,0 个其他字符。