Skip to main content
 首页 » 编程设计

python之检测 python 中的隐式子字符串模式

2024年09月07日42bjzhanghao

给定两个词,我想识别它的共同部分。

例如给定两个词"technology learning TEL" 和"learning TEL approach" 我想识别常用术语learning TEL .

再比如lightweight web applications和software web applications,常用术语是web applications

我当前的代码使用 in 如下。

for item1 in mylist_1: 
    for item2 in mylist_2: 
        if item2 in item1: 
            tmp_mylist1.append(item2) 
            break 
 
print(tmp_mylist1) 

但是,它无法识别隐含的单词短语,正如我在上面的示例中提到的那样。

if "technology learning TEL" in "learning TEL approach": 
    print("done") 
else: 
    print("no") 

因此,有没有最快的方法来识别 python 中这些隐含的常见连续术语?

请您参考如下方法:

确实存在更快的方法,但由于还没有人回答这里是一个解决方案:

import itertools 
 
def best_combination(string1, string2): 
    ''' 
    Gives best words combinations within both strings 
    ''' 
    words = string1.split() 
    # All possible solutions for a case 
    solutions = [] 
 
    # Loop to increment number of words combination to test 
    for i in range(1, len(words) + 1): 
        # get all possible combinations according to current number of words to test 
        possibilities = list(itertools.combinations(words, i)) 
 
        # test all possiblities 
        for possibility in possibilities: 
            tested_string = ' '.join(possibility) 
 
            # If it match, add it to solutions list 
            if tested_string in string2: 
                solutions.append(tested_string) 
 
    # Best solution is the longest 
    solutions.sort(key=len, reverse=True) 
    return solutions[0] 
 
 
print(best_combination('technology learning TEL', 'learning TEL approach')) 
print(best_combination('aaa bbb ccc', 'bbb ccc')) 
print(best_combination('aaa bbb ccc', 'aaa bbb ccc')) 
print(best_combination('aaa bbb ccc', 'ccc bbb')) 

输出:

learning TEL 
bbb ccc 
aaa bbb ccc 
bbb 

More about itertools.combinations


编辑

同样的事情,更少的行,更多的一行:

def best_combination(string1, string2): 
    ''' 
    Gives best words combinations within both strings 
    ''' 
    words = string1.split() 
    solutions = [] 
 
    tests = sum([list(itertools.combinations(words, i)) for i in range(1, len(words) + 1)], []) 
    for test in tests: 
        if ' '.join(test) in string2: 
            solutions.append(' '.join(test)) 
    solutions.sort(key=len, reverse=True) 
    return solutions[0]