如何根据单词列表对字符串中的单词进行分组?

2024-04-29 14:43:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个单词和一个字符串的列表,我想创建一个新的列表,如果一个列表中的相同单词在字符串中,而字符串的下一个单词也在字符串中,它会附加它们,并将它们存储为列表中的新元素。你知道吗

keyword_list = ['individual', 'fixed', 'treatments', 'deposit', 'health',
                'millions', 'panic', 'decision', 'policy', 'insurance', 'account']

string1 = 'i want to buy individual insurance policy and you can get upto 2 millions for the cover do not panic i also want to open fixed deposit account'

new_list = ['individual insurance policy',
            'millions', 'panic', 'fixed deposit account']

Tags: to字符串列表policyaccount单词individuallist
2条回答

'' 这是我提出的答案,我们可以改进它吗?我没有得到一个合适的答案 ''

speech=“即使你年轻健康,谁应该购买个人健康保险拥有个人健康保险是一个明智的决定”

关键字=['个人','健康','保险','存款','定期','帐户','保单','年轻']

新的\u键=[]

语音列表=演讲。分裂()

对于范围内的i(len(语音列表)-1):

if speech_list[i] in keyword:

    word = speech_list[i]

    for x in range(i+1,len(speech_list)-1):

        if speech_list[x] in keyword:

            word+=" "+speech_list[x]

        else:

            break;

    new_key.append(word)

打印(新的\u键)

''代码输出-['个人健康保险单','健康保险单','保险单','保单','年轻','个人健康保险','健康保险','保险']''

''预期输出-['个人健康保险单','年轻','个人健康保险']''

您可以根据元素在keyword_list中的存在情况对它们进行分组,并使用" "加入这些组。你知道吗

>>> data = 'i want to buy individual insurance policy and you can get upto 2 millions for the cover do not panic i also want to open fixed deposit account'
>>> keyword_list = ['individual', 'fixed', 'treatments', 'deposit', 'health',
...                 'millions', 'panic', 'decision', 'policy', 'insurance', 'account']

现在,让我们将keyword_list转换为一个集合,这样查找会更快。你知道吗

>>> keys = set(keyword_list)

现在,让我们根据单词在data中的出现情况来对keys中的单词进行分组,如下所示

>>> from itertools import groupby
>>> [" ".join(grp) for res, grp in groupby(data.split(), keys.__contains__) if res]
['individual insurance policy', 'millions', 'panic', 'fixed deposit account']

对于传递给groupby的集合中的每个元素,在本例中它是data.split(),将调用keys.__contains__函数。并基于该函数调用的结果,形成组。因为我们只对存在于keys中的项目感兴趣,所以我们在列表理解中使用if res进行过滤。你知道吗

相关问题 更多 >