简体   繁体   中英

how to perform a union between two strings while preserving order and appropriate html tags

I have two texts. One is the original. The other is a modified version of the original: it has some words removed and html tags added to some words. Example:

orginal_text = "Pay me some good respect!"
modified_text = "Pay <span>some respect!</span>"

I'm looking to merge the two to add back the removed words and get the following:

Pay me <span>some</span> good <span>respect!</span>

In the example there was: <span>some respect!</span> but I want to put back good but not include it in the tag. So: <span>some</span> good <span>respect!</span>

This works; mind you, if the "spanned" words in the modified_text appear elsewhere in the original text, this will not yield the expected result:

original_text = "Pay me some good respect!"
modified_text = "Pay <span>some respect!</span>"

sps, spe = '<span>', '</span>'
sptext = modified_text.split(sps)[1].split(spe)[0]
merged_text = original_text
for word in sptext.split():
    merged_text = merged_text.replace(word, sps+word+spe)

Result:

merged_text
Out[66]: 'Pay me <span>some</span> good <span>respect!</span>'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM