首页 > 解决方案 > 检查文本是否包含字符串并保留原​​始文本中匹配的单词:

问题描述

a = "Beauty Store is all you need!"
b = "beautystore"
test1 = ''.join(e for e in a if e.isalnum())
test2 = test1.lower() 
test3 = [test2]
match = [s for s in test3 if b in s]
if match != []:
    print(match)
>>>['beautystoreisallyouneed']

我想要的是:“美容店”

我在字符串中搜索关键字,我想以字符串的原始格式(大写字母和空格之间)从字符串中返回关键字,但只返回包含关键字的部分。

标签: python-3.x

解决方案


如果关键字只出现一次,这将为您提供正确的解决方案:

a = "Beauty Store is all you need!"
b = "beautystore"

ind = range(len(a))

joined = [(letter, number) for letter, number in zip(a, ind) if letter.isalnum()]

searchtext = ''.join(el[0].lower() for el in joined)

pos = searchtext.find(b)

original_text = a[joined[pos][1]:joined[pos+len(b)][1]]

它保存每个字母的原始位置,将它们连接到小写字符串,找到位置,然后再次查找原始位置。


推荐阅读