计算熊猫数据框中的左括号

问题描述

我正在尝试在数据帧列中使用 python 中的 string.punctuation 模块计算符号数,但我找不到一种方法来计算左括号,因为 python 认为它显然不认为它是一个字符串。

我正在研究 linux + Jupyter notebook 和 python 3.8。

df = pd.DataFrame()
df['password'] = data
df['sign'] = 0
for i in string.punctuation:
    print(i)
    print(type(i))
    df['sign'] += df['password'].str.count(i)
    
df['sign'].iloc[:100]

这给了我:

!
<class 'str'>
"
<class 'str'>
#
<class 'str'>
$
<class 'str'>
%
<class 'str'>
&
<class 'str'>
'
<class 'str'>
(
<class 'str'>

然后是异常:

/opt/conda/lib/python3.8/sre_parse.py in _parse(source,state,verbose,nested,first)
    834             p = _parse_sub(source,sub_verbose,nested + 1)
    835             if not source.match(")"):
--> 836                 raise source.error("missing ),unterminated subpattern",837                                    source.tell() - start)
    838             if group is not None:

error: missing ),unterminated subpattern at position 0

谢谢。

解决方法

示例数据框:

df = pd.DataFrame({'text': ['hel\\l\'o','hellO()world']})

括号是正则表达式语法的一部分,因此您需要对它们进行转义:

df['text'].str.count('\(')

要涵盖所有 string.punctuation,您可以使用:

df['text'].str.count(f'[{re.escape(string.punctuation)}]')
,

我用过这个,如果有人来这里也能用:

count = lambda l1,l2: sum([1 for x in l1 if x in l2])
df['punctuation'] = df['password'].apply(lambda s: count(s,string.punctuation))

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...