如何使用Python pandas查找给定系列中每个单词中出现了不止一个特殊字符的数量总和?
输入 -假设您有一个系列,
0 水果!!
1 *蛋糕*
2 $坚果
3 #饮料
dtype:object
输入 -系列中不止一个特殊字符的计数总数的结果为2。
让我们尝试找到此问题的不同解决方案。
解决方案1
为了解决这个问题,我们将遵循下面的步骤 –
- 定义一个系列
-
创建特殊字符值列表。
-
将特殊字符和总特殊字符计数的初始值设置为0。
-
创建for循环并逐个访问系列中的所有值,并创建if条件来比较基于特殊字符的值,如下所示-
for i in data:
chars_count = 0
for j in list(i):
if j in special_char:
chars_count = chars_count+1
- 设置if条件并检查计数值。如果count>1,则打印总计数。
定义如下 –
if(chars_count>1):
total_count = total_count+1
print(total_count)
解决方案2
或者,我们可以使用正则表达式和lambda函数过滤方法找到总数。
为了解决这个问题,我们将遵循下面的步骤 –
- 定义一个系列
-
将lambda过滤方法应用于基于特殊字符的输入进行验证()。
-
找到长度大于1。它如下所定义 –
l=["水果!!","*蛋糕*","$坚果","#饮料"]
data=pd.Series(filter(lambda
x:1<len(re.findall(r"\W",x)),l))
例子
让我们看一下实现,以获取更好的了解 –
import pandas as pd
import string
l = ["Fruits!!","*Cakes*","$Nuts","#Drinks"]
data = pd.Series(l)
chars=string.punctuation
special_char=list(chars)
total_count = 0
for i in data:
chars_count = 0
for j in list(i):
if j in special_char:
chars_count = chars_count+1
if(chars_count>1):
total_count = total_count+1
print(total_count)
解决方案3
例子
import pandas as pd
import re
l=["水果!!","*蛋糕*","$坚果","#饮料"]
data=pd.Series(filter(lambda x:1<len(re.findall(r"\W",x)),l))
print("count:",len(data))
输出
上述程序的输出如下 –
2