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

Cách tìm tất cả trạng từ (adverb) và vị trí trong văn bản bằng Python Regex

Dùng re.finditer() để lấy cả nội dung match VÀ vị trí (start/end) của từng match. Ví dụ tìm các từ kết thúc bằng "ly" (trạng từ tiếng Anh phổ biến).

Ví dụ từ tài liệu Python

import re

text = "He was carefully disguised but captured quickly by police."

# \w+ly : từ kết thúc bằng 'ly'
for m in re.finditer(r'\w+ly', text):
    print(f'{m.start():02d}-{m.end():02d}: {m.group()}')

Kết quả


07-16: carefully
40-47: quickly

Giải thích

  • re.finditer() trả về iterator của MatchObject.
  • m.start(): Vị trí bắt đầu (index) của match.
  • m.end(): Vị trí kết thúc (index sau ký tự cuối).
  • m.span(): Tuple (start, end).
  • m.group(): Nội dung match.

Cải tiến pattern cho trạng từ chính xác hơn


# Trạng từ thường: ly, nhưng không phải family, likely, early...
# Cần negative lookbehind hoặc word boundary tốt hơn
pattern = r'\b\w+ly\b'  # Word boundary

# Hoặc loại trừ một số từ giả dương
exclude = r'(?

Ứng dụng: Highlight matches trong text


def highlight_adverbs(text):
    pattern = r'\b\w+ly\b'
    result = []
    last_end = 0
    for m in re.finditer(pattern, text):
        result.append(text[last_end:m.start()])
        result.append(f'**{m.group()}**')  # Markdown bold
        last_end = m.end()
    result.append(text[last_end:])
    return ''.join(result)

print(highlight_adverbs("He walked slowly and spoke quietly."))
# He walked **slowly** and spoke **quietly**.

Tại sao dùng finditer() thay vì findall()?

  • findall() chỉ trả về list strings, không có vị trí.
  • finditer() cho phép truy cập .start(), .end(), .span().
  • Hữu ích cho: syntax highlighting, error reporting, text annotation, diff tools.