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

Chương trình sắp xếp cụm từ theo số lần xuất hiện trong Python


Mô tả bài toán

Cho danh sách phrases và danh sách sentences. Sắp xếp phrases theo số lần xuất hiện trong sentences (giảm dần). Nếu bằng nhau, giữ thứ tự gốc.

Ví dụ

phrases = ['strong', 'durable', 'efficient'], sentences = ['the product is durable and efficient', 'strong and durable', 'it is efficient', 'like it because it is efficient']. Kết quả: ['efficient', 'durable', 'strong'].

Giải thuật

  1. Khởi tạo từ điển cnt đếm lần xuất hiện cho mỗi phrase.
  2. Duyệt từng câu, tách từ thành tập hợp, tăng đếm cho phrase có trong tập hợp.
  3. Sắp xếp phrases theo (-cnt[phrase], index_nguyên).

Triển khai Python

def solve(phrases, sentences):
    cnt = {}
    for feature in phrases:
        cnt[feature] = 0
    for response in sentences:
        p = response.split()
        s = set(p)
        for i in s:
            if i in cnt:
                cnt[i] += 1
    res = [[k, cnt[k]] for k in cnt]
    res.sort(key=lambda x: (-x[1], phrases.index(x[0])))
    return [i[0] for i in res]

print(solve(['strong', 'durable', 'efficient'],
            ['the product is durable and efficient',
             'strong and durable',
             'it is efficient',
             'like it because it is efficient']))

Đầu vào

['strong', 'durable', 'efficient'], ['the product is durable and efficient', 'strong and durable', 'it is efficient', 'like it because it is efficient']

Đầu ra

['efficient', 'durable', 'strong']