with open('keyword.txt', 'r') as file:
keyword = [word.strip() for word in file.readlines()]
with open('file.txt', 'r') as file:
article = file.read()
unmatched_keywords = []
for word in keyword:
if word in article:
article = article.replace(word, f"<b>{word}</b>")
else:
unmatched_keywords.append(word)
print(article)
with open('unmatched_keywords.txt', 'w') as file:
for word in unmatched_keywords:
file.write(word + '\n')
一段代码,批量匹配关键词加粗,同时生成unmatched_keywords文件,用于储存未匹配的关键词;
在此基础上,如果想要一个关键词只匹配一次的话,应该如何修改?
import re
with open('keyword.txt', 'r') as file:
keyword = [word.strip() for word in file.readlines()]
with open('file.txt', 'r') as file:
article = file.read()
unmatched_keywords = []
for word in keyword:
pattern = re.compile(fr'\b{re.escape(word)}\b')
match = re.search(pattern, article)
if match:
article = re.sub(pattern, f"<b>{match.group()}</b>", article, count=1) #注意这里!!!
else:
unmatched_keywords.append(word)
print(article)
with open('unmatched_keywords.txt', 'w') as file:
for word in unmatched_keywords:
file.write(word + '\n')
不知道你这个问题是否已经解决, 如果还没有解决的话:import re
from collections import Counter
def highlight_keywords(text, keywords):
# 创建正则表达式模式,用于匹配关键词
pattern = re.compile('|'.join(keywords), re.IGNORECASE)
# 匹配关键词并加粗显示
def replace(match):
return f"<b>{match.group()}</b>"
highlighted_text = pattern.sub(replace, text)
# 找出未匹配到的关键词
matched_keywords = set(re.findall(pattern, text, re.IGNORECASE))
unmatched_keywords = list(set(keywords) - matched_keywords)
# 将未匹配到的关键词存储到unmatched_keywords文件
with open('unmatched_keywords.txt', 'w') as file:
file.write('\n'.join(unmatched_keywords))
return highlighted_text
# 测试
text = "This is a text with multiple keywords like apple, banana, and orange."
keywords = ['apple', 'banana', 'orange', 'mango']
highlighted_text = highlight_keywords(text, keywords)
print(highlighted_text)
代码说明: 1. 我们使用re
模块创建一个正则表达式模式,用于匹配关键词。re.IGNORECASE
参数表示对大小写不敏感。 2. replace()
函数用于替换匹配到的关键词为加粗的格式。 3. highlight_keywords()
函数接受一段文本和关键词列表作为参数。它使用正则表达式模式搜索匹配到的关键词,并用<b>
标签将其加粗显示。然后,它找出文本中未匹配到的关键词,并将其存储在unmatched_keywords.txt文件中。 4. 在测试部分,我们定义了一段文本和关键词列表。然后调用highlight_keywords()
函数,将返回的加粗文本打印出来。
要使每个关键词只匹配一次,可以使用re.sub()
函数来替换匹配到的关键词。修改replace()
函数如下:
def replace(match):
unmatched_keywords.remove(match.group())
return f"<b>{match.group()}</b>"
这样,每次匹配到一个关键词后,就从未匹配关键词列表中移除该关键词。同时,将未匹配的关键词列表存储到unmatched_keywords.txt
文件中。