一种解决方法是使用正则表达式,根据主题列表中的每个主题生成一个正则表达式,并通过遍历文本来找到与每个正则表达式匹配的所有文本段落。以下是一个示例代码:
import re
# 定义主题列表
topic_list = ['sports', 'technology', 'politics']
# 生成每个主题对应的正则表达式
topic_regex_list = []
for topic in topic_list:
topic_regex_list.append(re.compile(f"({topic})", flags=re.IGNORECASE))
# 待标记文本
text = "I like sports and technology. Politics is not my thing."
# 遍历文本,并按照顺序标记多个主题
result = []
for topic_regex in topic_regex_list:
match_list = re.findall(topic_regex, text)
for match in match_list:
result.append(match)
# 输出结果
print(result) # ['sports', 'technology', 'politics']
此示例代码将主题列表中的每个主题转换为正则表达式,并遍历文本以查找其出现的主题。 结果为按照其出现顺序标记多个主题的列表。
下一篇:按照其大小进行编号计划