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