python-3.x - 检查文本是否包含字符串并保留原始文本中匹配的单词:
问题描述
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']
我想要的是:“美容店”
我在字符串中搜索关键字,我想以字符串的原始格式(大写字母和空格之间)从字符串中返回关键字,但只返回包含关键字的部分。
解决方案
如果关键字只出现一次,这将为您提供正确的解决方案:
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]]
它保存每个字母的原始位置,将它们连接到小写字符串,找到位置,然后再次查找原始位置。
推荐阅读
- python - 基于txt文件使用Python对数据进行排序
- python - 从文本文件中删除随机选择
- firebase - Firestore 查询变量以填充共享首选项
- swift - dataTask 在展开可选值时意外发现 nil
- php - CodeIgniter -> 无法使用提供的设置连接到您的数据库服务器
- regex - 正则表达式 -> 检测模式 -> 将其移动到行首
- hive - 缺少 hive 执行 jar 3.1.2
- python - 创建 Azure 事件网格主题错误 - “无权执行操作”
- python - 使用 update_one 更新 pymongo 中的嵌套字典(python mongoDB)
- php - 如何划分三个类别的组合?