这是对 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/