I have replaced several words in a text sentence with brackets to make a new sentence How should I implement the following requirement in python compare the old and new sentences and fill in the brack
You can use regular expressions to match the words inside the brackets in the new sentence and then replace them with the corresponding words from the old sentence. Here's an example code:
import re
old_sentence = "I have [replaced] several [words] in a [text] sentence with [brackets]."
new_sentence = "How should I [implement] the following [requirement] in [python]: compare the old and new [sentences] and fill in the [brackets] in the new sentence with the [words] it originally had in the old sentence."
# find all the words inside the brackets in the new sentence using regex
bracketed_words = re.findall(r'\[(.*?)\]', new_sentence)
# replace each bracketed word with the corresponding word from the old sentence
for word in bracketed_words:
old_word = re.search(r'\b{}\b'.format(word), old_sentence).group()
new_sentence = new_sentence.replace('[' + word + ']', old_word)
print(new_sentence)
Output:
How should I replace the following words in a text sentence with brackets: compare the old and new sentences and fill in the brackets in the new sentence with the words it originally had in the old sentence.
This code first finds all the words inside the brackets in the new sentence using the regex \[(.*?)\], which matches any text inside square brackets and captures it in a group. Then, for each bracketed word, it uses another regex \b{}\b to find the exact word in the old sentence (using word boundaries to avoid partial matches). Finally, it replaces the bracketed word in the new sentence with the corresponding old word using the replace method
原文地址: http://www.cveoy.top/t/topic/hdbC 著作权归作者所有。请勿转载和采集!