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

Đếm từ trong câu Python

Bài toán: cho chuỗi, đếm số từ.

Cách 1: Dùng split()

split() tách chuỗi thành list, phân cách mặc định là khoảng trắng.

test_string = "Tutorials point is a learning platform"
print("The original string is : " + test_string)
res = len(test_string.split())
print("The number of words in string are : " + str(res))
The original string is : Tutorials point is a learning platform
The number of words in string are : 6

Cách 2: Dùng regex (re.findall)

findall(r'\w+', ...) tìm tất cả từ (chữ số, chữ cái, gạch dưới).

import re
test_string = "Tutorials point is a learning platform"
print("The original string is : " + test_string)
res = len(re.findall(r'\w+', test_string))
print("The number of words in string are : " + str(res))

Kết quả: 6 từ.

Cách 3: Dùng sum() + strip() + split()

Kiểm tra từng từ sau split, strip dấu câu, isalpha() để xác định từ hợp lệ, sum tổng.

import string
test_string = "Tutorials point is a learning platform"
print("The original string is: " + test_string)
res = sum([i.strip(string.punctuation).isalpha() for i in test_string.split()])
print("The number of words in string are : " + str(res))
The original string is : Tutorials point is a learning platform
The number of words in string are : 6

Kết luận

Đã học 3 cách đếm từ: split(), regex findall, sum+strip+split.