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

(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写入完成!')
相关推荐
未来可期叶2 小时前
如何用Python批量解压ZIP文件?快速解决方案
python
张槊哲2 小时前
ROS2架构介绍
python·架构
风逸hhh3 小时前
python打卡day29@浙大疏锦行
开发语言·前端·python
浩皓素3 小时前
深入理解For循环及相关关键字原理:以Python和C语言为例
c语言·python
英英_3 小时前
详细介绍一下Python连接MySQL数据库的完整步骤
数据库·python·mysql
水花花花花花3 小时前
GloVe 模型讲解与实战
python·深度学习·conda·pip
C_VuI3 小时前
如何安装cuda版本的pytorch
人工智能·pytorch·python
Star abuse3 小时前
机器学习基础课程-6-课程实验
人工智能·python·机器学习
不二一4 小时前
linux c++头文件生成源文件 使用python脚本 配置vim快捷键
linux·c++·python
RongSen334 小时前
Python海龟绘图(Turtle Graphics)核心函数和关键要点
开发语言·python