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

(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写入完成!')
相关推荐
顾林海3 小时前
Agent入门阶段-编程基础-Python:流程控制
python·agent·ai编程
呱呱复呱呱6 小时前
Django CBV 源码解读:一个请求是怎么找到你的 get() 方法的
python·django
曲幽10 小时前
刚部署的 LibreTranslate 频频翻车?我掏出了 20 年前的 StarDict 词典,用 FastAPI 搭了个本地词典翻译 API
python·fastapi·web·translate·goldendict·libretranslate·stardict·pystardict
荣码11 小时前
用Streamlit给AI应用套个界面,10行代码出Web页面
java·python
兵慌码乱20 小时前
基于Python+PyQt5+SQLite的药房管理系统实现:事务一致性与界面解耦全流程解析
python·sqlite·信号与槽·pyqt5·数据库设计·桌面应用开发·事务处理
金銀銅鐵1 天前
[Python] 体验用欧几里得算法计算最大公约数的过程
python·数学
FreakStudio1 天前
W55MH32L-EVB 上手测评:硬件 TCP/IP 加持的以太网单片机,MicroPython 零门槛开发
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
用户0332126663671 天前
使用 Python 从零创建 Word 文档
python
Csvn1 天前
Python 两大经典坑点 —— 可变默认参数 & 闭包延迟绑定
后端·python
曲幽1 天前
别再用网页翻译看源码了!你的私人翻译神器LibreTranslate,部署避坑指南来了
python·docker·web·pot·translate·libretranslate·arogstranslate