比较列表与Python中的字符串并突出显示匹配项

时间:2020-09-16 19:57:46

标签: python list compare string-formatting

我正在尝试将python列表与字符串进行比较,并在新字符串中突出显示带有mark的匹配项。 但这是行不通的。以下示例:

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)

1 个答案:

答案 0 :(得分:1)

也许是这样的:

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>
相关问题