Skip to main content
 首页 » 编程设计

Python字符串匹配并为不匹配的字符串给出重复的数字

2024年12月31日19mfryf

我在 list1 中设置了一些词:“管理咨询服务更好的财务健康”

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..] 

因此,任何匹配都会反射(reflect)在相应的位置,如 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中获得这样的预期结果?

请您参考如下方法:

您可以使用 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]