import re def highlight_common_words(common_words, sentences, title): color_map = {} highlighted_html = [] for idx, sentence in enumerate(sentences, start=1): highlighted_sentence = f"{idx}. {sentence}" for index, word in common_words: if word not in color_map: # Assign color using HSL for better visual distinction color_map[word] = f'hsl({(len(color_map) % 6) * 60}, 70%, 80%)' # Create a regex pattern for the word escaped_word = re.escape(word) pattern = rf'\b{escaped_word}\b' color = color_map[word] # Use a lambda function for word highlighting highlighted_sentence = re.sub( pattern, lambda m: (f'' f'{index}' f'{m.group(0)}' ''), highlighted_sentence, flags=re.IGNORECASE ) highlighted_html.append(highlighted_sentence) # Construct the final HTML output return generate_html(title, highlighted_html) def highlight_common_words_dict(common_words, sentences, title): color_map = {} highlighted_html = [] for idx, (sentence, score) in enumerate(sentences.items(), start=1): highlighted_sentence = f"{idx}. {sentence}" for index, word in common_words: if word not in color_map: color_map[word] = f'hsl({(len(color_map) % 6) * 60}, 70%, 80%)' escaped_word = re.escape(word) pattern = rf'\b{escaped_word}\b' color = color_map[word] highlighted_sentence = re.sub( pattern, lambda m: (f'' f'{index}' f'{m.group(0)}' ''), highlighted_sentence, flags=re.IGNORECASE ) highlighted_html.append( f'