如何将file.txt内的关键词(超过100)批量匹配file.word里的文章,并且关键词高亮
假设你的 file.txt每个单词一行:
with open('file.txt', 'r') as file:
keyword = [word.strip() for word in file.readlines()]
with open('file.word', 'r') as file:
article = file.read()
for word in keyword:
article = article.replace(word, f"<b>{word}</b>")
print(article)
不知道你这个问题是否已经解决, 如果还没有解决的话:我可以为您提供一种基于Python的解决方案。请按照以下步骤操作:
以下是一个示例代码,您可以根据实际情况进行调整:
import re
def highlight_keywords(keywords, text):
for keyword in keywords:
pattern = re.compile(re.escape(keyword), re.IGNORECASE)
text = pattern.sub('<strong>{}</strong>'.format(keyword), text)
return text
def batch_highlight(file_txt, file_word, output_file):
# 读取关键词列表
with open(file_txt, 'r') as f:
keywords = f.read().splitlines()
# 读取file.word文件内容
with open(file_word, 'r') as f:
text = f.read()
# 高亮处理关键词
highlighted_text = highlight_keywords(keywords, text)
# 保存处理后的文章
with open(output_file, 'w') as f:
f.write(highlighted_text)
# 调用批量处理函数
batch_highlight('file.txt', 'file.word', 'output.word')
在上述代码中,我们使用了正则表达式来进行关键词的匹配和替换。匹配时使用了re.escape函数来确保关键词中的特殊字符不会被当作正则表达式的元字符处理。
请将file.txt和file.word替换为实际的文件路径,运行代码后,将会生成一个新的output.word文件,其中关键词已经被加粗处理。
请注意,在使用正则表达式时,关键词的大小写不敏感,即无论关键词在文章中以何种大小写出现,都会被匹配和替换。如果您希望大小写敏感,请将re.IGNORECASE参数移除。
如果您需要进一步定制高亮样式,可以根据需要修改highlight_keywords函数中的代码。
希望这个解决方案能够帮到您。如果您有任何问题,请随时提问。