Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Đếm từ có hơn 1 ký tự đặc biệt trong Series Python

Mô tả bài toán

Cho Series:

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

Yêu cầu: Đếm số từ có hơn 1 ký tự đặc biệt (non-alphanumeric). Kết quả: 2 (fruits!! và *cakes*).

Giải pháp 1: Vòng lặp đếm ký tự đặc biệt (cách gốc)

import pandas as pd
import string

l = ["Fruits!!","*Cakes*","$Nuts","#Drinks"]
data = pd.Series(l)

special_chars = list(string.punctuation)  # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
total_count = 0

for word in data:
    char_count = 0
    for ch in word:
        if ch in special_chars:
            char_count += 1
    if char_count > 1:
        total_count += 1

print(f"Tổng số từ có >1 ký tự đặc biệt: {total_count}")

Giải pháp 2: Regex \W (non-word character) + filter (cách gốc)

\W khớp với ký tự không phải chữ/số/gạch dưới.

import pandas as pd
import re

l = ["fruits!!","*cakes*","$nuts","#drinks"]
data = pd.Series(l)

# Filter: độ dài list findall > 1
filtered = pd.Series(filter(lambda x: 1 < len(re.findall(r"\W", x)), l))
print(f"Count: {len(filtered)}")

Giải pháp 3: Vector hóa str.count (khuyên dùng)

import pandas as pd

data = pd.Series(["Fruits!!","*Cakes*","$Nuts","#Drinks"])

# Đếm ký tự đặc biệt cho mỗi từ
# Pattern: [^a-zA-Z0-9_] tương đương \W
special_counts = data.str.count(r'[^\w]')  # hoặc r'\W'
print("Số ký tự đặc biệt mỗi từ:")
print(special_counts)

# Đếm từ có >1
count = (special_counts > 1).sum()
print(f"\nTổng từ có >1 ký tự đặc biệt: {count}")

# Liệt kê các từ đó
words = data[special_counts > 1]
print("Các từ:")
print(words)

Đầu ra

Số ký tự đặc biệt mỗi từ:
0    2
1    2
2    1
3    1
dtype: int64

Tổng từ có >1 ký tự đặc biệt: 2

Các từ:
0    Fruits!!
1    *Cakes*
dtype: object

Lưu ý: \W bao gồm cả khoảng trắng. Nếu chuỗi có space, dùng [^\w\s] để loại trừ space. string.punctuation chỉ chứa punctuation, không có space.