python - 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中得到这样一个预期的结果?
解决方案
您可以使用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]
推荐阅读
- ios - 来自服务器 url 的拇指图像
- lua - source_file.lua:1:尝试调用一个 nil 值(全局“RegisterServerEvent”)
- android - 如何在服务中使用上下文?
- php - 我将如何使用 WPbakery 将此代码实施到我的 Wordpress 网站中
- java - 蛮力最长公共子序列
- svg - 如何在 SVG 中遮盖部分描边路径?
- docker - docker desktop 如何在 Windows 机器上运行 linux 容器
- angular6 - 如何检查 textarea 是否是焦点?
- php - 000webhost 没有从数据库中检索/获取数据,一些按钮和错误消息不起作用,但在 localhost 中它可以工作
- python - 是否有任何用于印地语单词搜索的 NLP 代码?