Skip to main content
 首页 » 编程设计

python之如何按照字符串的顺序识别子串

2025年05月04日32luoye11

我有一个句子列表如下。

sentences = ['data mining is the process of discovering patterns in large data sets involving methods at the intersection of machine learning statistics and database systems', 'data mining is an interdisciplinary subfield of computer science and statistics with an overall goal to extract information from a data set and transform the information into a comprehensible structure for further use','data mining is the analysis step of the knowledge discovery in databases process or kdd'] 

我还有一组选定的概念。

selected_concepts = ['machine learning','patterns','data mining','methods','database systems','interdisciplinary subfield','knowledege discovery','databases process','information','process'] 

现在我想按照句子的顺序从sentences中选择seleceted_concepts中的概念。

即我的输出应该如下所示。

output = [['data mining','process','patterns','methods','machine learning','database systems'],['data mining','interdisciplinary subfield','information'],['data mining','knowledge discovery','databases process']] 

我可以提取句子中的概念如下。

output = [] 
for sentence in sentences: 
    sentence_tokens = [] 
    for item in selected_concepts: 
        if item in sentence: 
             sentence_tokens.append(item) 
    output.append(sentence_tokens) 

但是,我很难根据句子顺序组织提取的概念。在 python 中有什么简单的方法吗?

请您参考如下方法:

一种方法是使用 .find() 方法找到子字符串的位置,然后按该值排序。例如:

output = [] 
for sentence in sentences: 
    sentence_tokens = [] 
    for item in selected_concepts: 
        index = sentence.find(item) 
        if index >= 0: 
             sentence_tokens.append((index, item)) 
    sentence_tokens = [e[1] for e in sorted(sentence_tokens, key=lambda x: x[0])] 
    output.append(sentence_tokens)