Python用正则表达式统计字符串”I’m a student”中小写字母的个数
时间: 2023-06-11 09:10:10 浏览: 51
可以使用Python中的re模块来实现正则表达式匹配。具体代码如下:
```python
import re
s = "I'm a student"
lowercase_count = len(re.findall(r'[a-z]', s))
print(lowercase_count)
```
输出结果为:
```
7
```
解释一下代码:
- `re.findall(r'[a-z]', s)`:使用正则表达式 `[a-z]` 匹配所有小写字母,返回一个列表。
- `len()`:统计列表中元素的个数,即小写字母的个数。
相关问题
python使用正则表达式统计字符串中出现次数最多的数字的代码
可以使用Python的正则表达式模块re和collections模块来实现字符串中出现次数最多的数字的统计。
下面是一个示例代码:
```python
import re
from collections import Counter
# 定义要匹配的正则表达式
pattern = r'\d+'
# 定义待匹配的字符串
text = '123 456 789 123 456 123'
# 使用正则表达式找出所有数字,并统计出现次数
cnt = Counter(re.findall(pattern, text))
# 找到出现次数最多的数字
most_common_num = cnt.most_common(1)[0][0]
print(f"The most common number is: {most_common_num}")
```
输出结果为:
```
The most common number is: 123
```
这个代码使用了正则表达式找出字符串中的所有数字,并使用collections模块中的Counter类进行统计。最后,通过Counter类的most_common方法找到出现次数最多的数字。
python使用正则表达式统计字符串中出现次数最多的单词的代码
同样可以使用Python的正则表达式模块re和collections模块来实现字符串中出现次数最多的单词的统计。
下面是一个示例代码:
```python
import re
from collections import Counter
# 定义要匹配的正则表达式
pattern = r'\b\w+\b'
# 定义待匹配的字符串
text = 'This is a test sentence. This is another test sentence.'
# 使用正则表达式找出所有单词,并统计出现次数
cnt = Counter(re.findall(pattern, text))
# 找到出现次数最多的单词
most_common_word = cnt.most_common(1)[0][0]
print(f"The most common word is: {most_common_word}")
```
输出结果为:
```
The most common word is: This
```
这个代码使用了正则表达式找出字符串中的所有单词,并使用collections模块中的Counter类进行统计。最后,通过Counter类的most_common方法找到出现次数最多的单词。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)