Skip to main content
 首页 » 编程设计

python之根据字典值集对字符串进行评分

2024年12月31日20luoye11

我有一个字符串

strA='ABCCBAAABBCCABABC' 

和一个长度小于 strA(比如长度 4)的字典(列表列表),它具有每个字符在给定位置出现的概率:

{"A":[0.4, 0.5, 0.1, 0.2], "B": [0.3, 0.5, 0.3, 0.6], "C":[0.3, 0.0, 0.6, 0.2]} 

我现在想要一个长度为 4 的滑动窗口,并根据这本字典对我的整个 strA 进行评分。 所以 srtA 的前 4 个字符是 ABCC,根据字典,分数将是:

(p(A) at pos0)*(p(B) at pos1)*(p(C)at pos2)*(p(C) at pos(3)) 

=0.4*0.5*0.6*0.2 =0.024

现在我想以 1 为增量滑动此窗口,并找到此窗口长度的整个字符串的最高得分。

现在我的做法是:

    score_new=0 
    window_len=4 
    for a in range(0,(len(strA)-window_len): 
            slide=strA[a:a+window_len] 
 
            score=1 
            for b in range(0,len(silde)): 
                score=score*(dict[slide[b]][b]) 
 
            if score>score_new: 
                score_new=score 
 
        return score_new 

这有效但很耗时。我必须对具有 1000 个不同长度可变窗口的 10000 个字符串进行评分,每个窗口都有不同的概率字典。

有没有更快的方法根据概率字典对字符串进行评分并只返回最高分?

请您参考如下方法:

这是我想出的:

def compute_best_score(test_string, prob_dict, window_size): 
    # assertion to check for uniform lengths 
    assert(all([len(prob_list) == window_size for prob_list in prob_dict.values()])) 
    best_window_index = -1 
    best_window_score = 0 
    for index, letter in enumerate(test_string): 
        # ignore last region of test_string as a window cannot be computed 
        if index > len(test_string) - window_size: 
            break 
        current_window_score = 1.0 
        for score_index in range(window_size): 
            current_char = test_string[index + score_index] 
            letter_scores = pdict[current_char] 
            current_window_score *= letter_scores[score_index] 
        if current_window_score > best_window_score: 
            best_window_score = current_window_score 
            best_window_index = index 
    return best_window_score, best_window_index 

在我使用的 python 下,这个似乎比基于 reduce 的答案表现更好(这让我感到惊讶)。这是我进行的简单分析运行的链接:

http://tpcg.io/S05WeL