単語のリストと文字列があり、リストの同じ単語が文字列に含まれていて、文字列の次の単語も文字列に含まれている場合は、新しいリストを作成したいので、それらを新しい要素として追加します。リスト。
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']
内の存在に基づいて要素を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
ます。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加