从字符串中匹配多个关键词,优先匹配更长的关键词

(1)把关键词按长度排序

(2)循环匹配关键词

(3)匹配到之后,就把关键词从字符串中删除

(4)继续匹配其他关键词

python 复制代码
import pandas as pd
import re

keyword_list = ['iPhone', 'iPhone 13 Pro', 'iPhone 13']

keyword_list = sorted(keyword_list, key=lambda x: len(x), reverse=True)

# 提取字符串中的关键词(忽略大小写和空格)
def extract_keywords(text_str):
    # 去除字符串中的所有空格,并小写
    text_str = re.sub(r'\s+', '', text_str).lower()
    matched_keywords = []
    # 遍历关键词列表
    for keyword in keyword_list:
        # 去除关键词中的空格,并小写
        keyword_re = re.sub(r'\s+', '', keyword).lower()
        # 检查关键词是否出现在字符串中
        if re.search(keyword_re, text_str):
            # 将匹配到的关键词原词加入匹配到的列表中
            matched_keywords.append(keyword)
            # 从字符串中删除匹配到的关键词
            text_str = text_str.replace(keyword_re, "")
    # 返回提取结果,使用逗号分隔
    return ', '.join(matched_keywords)


text_str = '''
iPhone 13和iPhone 13 Pro是同一代产品,都是iPhone家族的一员
'''

matched_keywords = extract_keywords(text_str)
print(matched_keywords)

# 批量处理

# # 关键词所在的excel表
# df1 = pd.read_excel(r'D:\关键词文件.xlsx')
# # 字符串所在的excel表
# df2 = pd.read_excel(r'D:\字符串文件.xlsx')


# # 获取df1中的关键词列表,并按长度排序
# keyword_list = sorted(df1['关键词'].tolist(), key=lambda x: len(x), reverse=True)
# print(keyword_list)

# 应用提取函数
# df2['提取结果'] = df2['字符串'].apply(extract_keywords)
# # 查看结果
# # print(df2)

# df2.to_excel(r'D:\提取结果.xlsx')
# print('excel写入完成!')
相关推荐
小小测试开发4 小时前
安装 Python 3.10+
开发语言·人工智能·python
梦想不只是梦与想5 小时前
Python 中的装饰器
python·装饰器
我叫唧唧波6 小时前
Python+AI 全栈学习笔记
人工智能·python·学习
copyer_xyf6 小时前
Python 异常处理
前端·后端·python
麻雀飞吧7 小时前
期货多合约策略目标持仓怎么更新才不乱
python·区块链
Cthy_hy7 小时前
拓扑排序超详解:原理 + Kahn 贪心算法
python·算法·贪心算法
LSssT.7 小时前
【01】Python 机器学习
开发语言·python
为爱停留7 小时前
给智能体装上「刹车」:中断(Interrupts)与人工审批全解析
python
l1t7 小时前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程39-40
开发语言·python
曾阿伦8 小时前
Python 搭建简易HTTP服务
开发语言·python·http