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

(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写入完成!')
相关推荐
Scott9999HH2 小时前
【IIoT流量实战】蒸汽管道阀门全关却仍有流量?用 Python 实现涡街信号 FFT 频谱分析与温压全补偿积算网关,深度拆解靠谱的涡街流量计厂家硬核技术标准
开发语言·python
AI云海3 小时前
python 列表、元组、集合和字典
开发语言·python
二十雨辰4 小时前
[爬虫]-Urllib
爬虫·python
玉鸯5 小时前
Agent Hook:在概率推理之上,为 Agent 叠加确定性控制
python·langchain·agent
weixin_446260856 小时前
HACO:面向动态部署环境的对冲式智能计算可靠多智能体调度框架
后端·python·flask
我的xiaodoujiao6 小时前
API 接口自动化测试详细图文教程学习系列32--Allure测试报告2
python·学习·测试工具·pytest
qetfw7 小时前
MXU:Tauri 2 + React 的 MaaFramework 跨平台 GUI 源码
前端·python·react.js·前端框架·开源项目·效率工具
用户8356290780517 小时前
Python 实现 Excel 页面布局与打印设置自动化
后端·python
一次旅行8 小时前
Python+大模型端到端自动化日报系统
开发语言·python·自动化