如何使用 Python Pandas 查詢給定序列中每個單詞中出現多個特殊字元的總計數?
輸入 - 假設你有一個序列,
0 fruits!! 1 *cakes* 2 $nuts 3 #drinks 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 條件並檢查計數值。如果計數 > 1,則列印總計數。
定義如下:
if(chars_count>1): total_count = total_count+1 print(total_count)
方案 2
或者,我們可以使用正則表示式和 lambda 函式 filter 方法來查詢總計數。
為了解決這個問題,我們將遵循以下步驟:
定義一個序列
應用 lambda filter 方法根據特殊字元()驗證輸入。
查詢長度是否大於一。定義如下:
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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP