gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:43 25 4
gpt4 key购买 nike

我有一个句子列表如下。

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)

关于python - 如何按照字符串的顺序识别子串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53844483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com