如何使用Python Pandas查找给定系列中每个单词中出现的一个以上特殊字符的总数?

输入-假设您有一个系列,

0       fruits!!
1       *cakes*
2       $nuts
3       #drinks
dtype: object

输入-系列中一个以上特殊字符的计数总数的结果为2。

让我们尝试为这个问题找到不同的解决方案。

解决方案1

为了解决这个问题,我们将遵循以下步骤-

  • 定义系列

  • 创建特殊字符值列表。

  • 将特殊字符的初始值和特殊字符总数设为0。

  • 创建一个for循环并一个接一个地访问Series中的所有值,并创建一个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过滤器方法以基于特殊char()验证输入。

  • 发现长度不止一个。它定义如下-

l=["fruits!!","*cakes*","$nuts","#drinks"]
               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=["fruits!!","*cakes*","$nuts","#drinks"]
data=pd.Series(filter(lambda x:1<len(re.findall(r"\W",x)),l))
print("count:",len(data))
输出结果

上面程序的输出如下-

2