Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ใช้ Python Pandas นับจำนวนคำที่มีอักขระพิเศษมากกว่า 1 ตัวใน Series


อินพุต - สมมติคุณมี series

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

เอาต์พุต - ผลลัพธ์จำนวนคำที่มีอักขระพิเศษมากกว่า 1 ตัว คือ 2

วิธีที่ 1

ทำตามขั้นตอนด้านล่าง

  • สร้าง Series

  • สร้างลิสต์อักขระพิเศษ

  • ตั้งค่าเริ่มต้นนับอักขระพิเศษและรวมเป็น 0

  • วนลูปนับอักขระพิเศษในแต่ละคำ

for i in data:
    chars_count = 0
    for j in list(i):
        if j in special_char:
            chars_count = chars_count+1
  • ถ้านับได้มากกว่า 1 ให้เพิ่มนับรวม

if(chars_count>1):
    total_count = total_count+1
    print(total_count)

วิธีที่ 2

ใช้ regular expression และ lambda filter

  • สร้าง series

  • ใช้ lambda filter ตรวจสอบจำนวนอักขระพิเศษมากกว่า 1

l=["fruits!!","*cakes*","$nuts","#drinks"]
data=pd.Series(filter(lambda x:1

ตัวอย่าง

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

ผลลัพธ์

2