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

Xóa phụ âm khỏi chuỗi trong Python

Dễ nhất dùng regular expression. Tách nhiều ký tự bằng "|" và dùng re.sub(chars_to_replace, string_to_replace_with, str). Ví dụ:

>>> import re
>>> consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
>>> re.sub('|'.join(consonants), "", "Hello people", flags=re.IGNORECASE)
"eo eoe"

Lưu ý: cũng dùng [] tạo group ký tự replace trong regex.

Nếu chỉ muốn giữ nguyên âm, xóa tất cả ký tự khác (kể cả space, số), dùng phiên bản dễ hơn:

>>> import re
>>> re.sub('[^aeiou]', "", "Hello people", flags=re.IGNORECASE)
"eoeoe"

Cũng lọc phụ âm như sau:

>>> consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
>>> s = "Hello people"
>>> ''.join(c for c in s if c.lower() not in consonants)
'eo eoe'