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

Crawl và tìm từ có thứ tự chữ cái trong từ điển Python

Thu thập danh sách từ từ URL, lọc các từ có ký tự theo thứ tự bảng chữ cái (ASCII tăng dần).

Quy trình

  1. Dùng requests tải file .txt từ web.
  2. Decode UTF-8, tách thành list từ.
  3. Duyệt từng từ, so sánh ASCII của ký tự liền kề.
  4. Nếu mọi cặp ký tự đều tăng dần → từ "ordered".

Code

import requests

def fetch_words(url):
    resp = requests.get(url)
    return resp.content.decode("utf-8").split()

def find_ordered_words():
    words = fetch_words("URL_CUA_FILE_TXT")  # Thay URL thực
    words = words[16:]  # Bỏ header nếu có
    for word in words:
        if len(word) < 3:
            continue
        ordered = True
        for i in range(len(word)-1):
            if ord(word[i]) > ord(word[i+1]):
                ordered = False
                break
        if ordered:
            print(f"{word}: ordered")

if __name__ == '__main__':
    find_ordered_words()

Ví dụ từ ordered

  • abc (97<98<99) ✓
  • almost (a
  • python (p>y? không) ✗

Cải tiến

  • Dùng all(ord(w[i]) <= ord(w[i+1]) for i in range(len(w)-1)).
  • Xử lý chữ hoa/thường: word.lower().
  • Lưu kết quả ra file.