python - findall 内的正则表达式 vs 计数内的正则表达式

标签 python regex pandas

这是对 How to count characters in a string? 的后续问题和Find out how many times a regex matches in a string in Python

我想计算字符串中的所有字母字符:

'Go until jurong point, crazy.. Available only in bugis n great world la e buffet... Cine there got amore wat...'

str.count() 方法允许对特定字母进行计数。如何使用计数方法计算字符串中整个字母表中的任何字母?

我试图在计数方法中使用正则表达式,但它返回 0 而不是 83。我使用的代码是:

import re

spam_data['text'][0].count((r'[a-zA-Z]'))

当我使用时:

len(re.findall((r'[a-zA-Z]'), spam_data['text'][0])) 它返回 83 的长度。

为什么 count 在这里返回 0?

最佳答案

你应该使用 str.count而不是计数。

spam_data['text'].str.count('\w')

0    83
Name: text, dtype: int64

要访问第一个值,请使用:

spam_data['text'].str.count('\w')[0]
83

关于python - findall 内的正则表达式 vs 计数内的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52882843/

相关文章:

python - Django:没有名为 context_processors 的模块,基本 URL

Python 内存泄漏 - 为什么会发生?

正则表达式修剪前导空格

python - Pandas read_csv 到多个 DataFrame 中

python - 根据另一列中的值替换 pandas df 中的值

python - 如何使用 Python 3 构建网络爬虫?

用于创建图像镜像并将其与一定量的白色混合的 Python 代码。

java正则表达式量词

正则表达式替换所有不适用于德语变音符号的小写单词

python - 导入 Pandas 时导致大量内存提交的原因