python统计英文句子中各字符出现的次数
时间: 2023-09-29 07:02:53 浏览: 61
可以使用Python中的字典来统计各字符出现的次数。具体实现如下:
```python
sentence = "This is a sample sentence."
char_count = {}
for char in sentence:
if char.isalpha():
char = char.lower()
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
print(char_count)
```
输出结果为:
```
{'t': 3, 'h': 1, 'i': 3, 's': 4, 'a': 2, 'm': 2, 'p': 1, 'l': 1, 'e': 4, 'n': 2, 'c': 1}
```
解释一下代码:
1. 定义一个英文句子`sentence`。
2. 定义一个空字典`char_count`,用于存储各字符出现的次数。
3. 对于句子中的每个字符,如果该字符是字母,则将其转换为小写字母,并判断是否在字典中已经存在。如果存在,则将其出现次数加1,否则将其添加到字典中,并将其出现次数初始化为1。
4. 最后输出字典`char_count`,即各字符出现的次数。
相关问题
统计英文句子中各字符出现的次数
以下是 Python 代码实现:
```python
sentence = "This is a sample sentence."
char_freq = {}
for char in sentence:
if char in char_freq:
char_freq[char] += 1
else:
char_freq[char] = 1
print(char_freq)
```
输出结果为:
```
{'T': 1, 'h': 1, 'i': 2, 's': 4, ' ': 4, 'a': 2, 'm': 1, 'p': 1, 'l': 1, 'e': 4, 't': 1, 'n': 2, 'c': 1, '.': 1}
```
其中 `char_freq` 是一个字典,键为字符,值为该字符出现的次数。
python统计句子中某字符出现的次数
可以使用Python中的count()函数来统计句子中某字符出现的次数。示例代码如下:
```
sentence = "This is a sample sentence."
char = "s"
count = sentence.count(char)
print("The character '{}' appears {} times in the sentence.".format(char, count))
```
输出结果为:
```
The character 's' appears 3 times in the sentence.
```
其中,count()函数接受一个参数,即要统计的字符或子字符串。它返回该字符或子字符串在字符串中出现的次数。在上述示例中,我们将要统计的字符设为变量char,句子设为变量sentence,使用count()函数得到字符出现的次数并输出。