Xử lý file văn bản: đếm từ, ký tự, độ dài trung bình, stop words, ký tự đặc biệt, số, từ viết hoa.
1. Đếm số từ
filename = "css3.txt"
try:
with open(filename) as f:
contents = f.read()
except FileNotFoundError:
print(f"File {filename} không tồn tại")
else:
words = contents.split()
print(f"Tổng số từ: {len(words)}")
# Output: 3574
2. Đếm ký tự
words = contents.split()
characters = sum(len(w) for w in words)
print(f"Tổng ký tự: {characters}") # 17783
3. Độ dài từ trung bình
avg = sum(len(w) for w in words) / len(words)
print(f"Độ dài TB: {avg:.2f}") # 4.97
4. Stop words (từ dừng) với NLTK
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
sent = "This is a sample sentence"
stop_words = set(stopwords.words('english'))
tokens = word_tokenize(sent)
filtered = [w for w in tokens if w.lower() not in stop_words]
print(tokens) # ['This', 'is', 'a', 'sample', 'sentence']
print(filtered) # ['sample', 'sentence']
5. Ký tự đặc biệt (ví dụ: #, @)
import collections as ct
special = "#"
count = sum(v for k,v in ct.Counter(words).items() if k in special)
print(f"Số ký tự đặc biệt: {count}")
6. Đếm số (numeric)
numeric = sum(map(str.isdigit, contents.split()))
print(f"Số lượng từ là số: {numeric}") # 2
7. Từ viết hoa toàn bộ
upper = sum(map(str.isupper, contents.split()))
print(f"Từ viết hoa: {upper}") # 121
Ứng dụng
- Phân tích sentiment, từ khóa SEO.
- Làm sạch dữ liệu NLP.
- Thống kê ngôn ngữ học.