首页 > 解决方案 > Python字符串匹配并为不匹配的字符串给出重复的数字

问题描述

我在中设置了一些单词list1"management consultancy services better financial health"

user_search="management consultancy services better financial health"
user_split = nltk.word_tokenize(user_search)
user_length=len(user_split)

分配:管理=1,咨询=2,服务=3,更好=4,财务=5,健康=6。然后将其与一组列表进行比较。

list2: ['us',
 'paleri',
 'home',
 'us',
 'consulting',
 'services',
 'market',
 'research',
 'analysis',
 'project',
 'feasibility',
 'studies',
 'market',
 'strategy',
 'business',
 'plan',
 'model',
 'health',
 'human' etc..]

因此,任何匹配都会反映在相应的位置上,如 1,2 3 等。如果位置不匹配,则位置将在单词上用数字 6 填充。预期输出示例:

[1]  7 8 9 10 11 3  12 13 14 15 16 17 18 19 20 21 22 6 23 24

这意味着字符串 3 和 4,即。此列表中有服务和健康(匹配)。其他数字表示不匹配。user_length=6. 所以不匹配的位置将从7开始。如何在python中得到这样一个预期的结果?

标签: pythonstringpython-3.xnltkcounter

解决方案


您可以使用itertools.count创建一个计数器并通过以下方式进行迭代next

from itertools import count

user_search = "management consultancy services better financial health"
words = {v: k for k, v in enumerate(user_search.split(), 1)}

# {'better': 4, 'consultancy': 2, 'financial': 5,
#  'health': 6, 'management': 1, 'services': 3}

L = ['us', 'paleri', 'home', 'us', 'consulting', 'services',
     'market', 'research', 'analysis', 'project', 'feasibility',
     'studies', 'market', 'strategy', 'business', 'plan',
     'model', 'health', 'human']

c = count(start=len(words)+1)
res = [next(c) if word not in words else words[word] for word in L]

# [7, 8, 9, 10, 11, 3, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 6, 23]

推荐阅读