python - 将列表与 Python 中的字符串进行比较并突出显示匹配项
问题描述
我正在尝试将 python 列表与字符串进行比较,并在新字符串中突出显示与标记匹配的内容。但它不会起作用。以下示例:
my_string = 'This is my string where i would find matches of my List'
my_list = ['THIS IS', 'WOULD FIND', 'BLA', 'OF MY LIST']
result_that_i_need = '<mark>This is</mark> my string where i <mark>would find</mark> matches <mark>of my List</mark>'
有谁知道如何解决这个问题?有人可以帮我吗?
我试过以下:
my_string = 'This is my string where i would find matches of my List'
my_string_split = string.split()
my_list = ['This is', 'would find', 'bla', 'of my List']
input_list=[]
for my_li in my_list:
if my_li in my_string:
input_list.append(my_li)
input_list_join = " ".join(input_list)
new_list = []
for my_string_spl in my_string_split:
if my_string_spl in input_list_join:
new_list.append('<mark>'+ my_string_spl + '</mark>')
else:
new_list.append(my_string_spl)
result = " ".join(new_list)
print(result)
解决方案
也许是这样的:
my_string = 'This is my string where i would find matches of my List'
my_list = ['This is', 'would find', 'bla', 'of my List']
result = my_string
for match in my_list:
if match in my_string:
result = result.replace(match, '<mark>' + match + '</mark>')
print(result)
输出:
<mark>This is</mark> my string where i <mark>would find</mark> matches <mark>of my List</mark>
推荐阅读
- sql - 如何序列化为json数组?
- windows - 如何将 ssh 设置到我的计算机的 github?
- python - 有没有办法在 python 中生成不同的对象实例?
- sql-server - .NET Code First 将用户登录添加为默认表架构
- javascript - 如何等待 load() 完成并在选择器中获取变量
- git - 如何在 GitLab 11.11 版中配置全局 git 挂钩?
- javascript - Thingsboard,从小部件的 javascript 访问服务器端属性
- ios - UIButton 失去响应(即无法按下它),可能是因为 CGAffineTransform
- assembly - LDR 指令 CortexM7 上的 UNALIGNED 使用错误
- typescript - $ref 类型转换导致编译器需要分号来终止行