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

(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写入完成!')
相关推荐
tsfy20038 分钟前
Python批量调整Excel格式,并排版导出PDF
python·pdf·excel
木囧21 分钟前
PyCharm手动创建虚拟环境
ide·python·pycharm
李可以量化25 分钟前
QMT 量化实践:两种方式获取个股上市日期(内置 Python + 原生 Python 完整可运行代码)
python
是多巴胺不是尼古丁33 分钟前
期末java复习--string
java·开发语言·python
garmin Chen1 小时前
从 Transformer 到 Agent:大模型技术全景解析
java·人工智能·python·深度学习·transformer
没有钱的钱仔1 小时前
pytorch_cuda安装
人工智能·pytorch·python
Full Stack Developme1 小时前
Apache Tika 教程
java·开发语言·python·apache
笨笨没好名字1 小时前
Leetcode刷题python版第一周
python·算法·leetcode
Cthy_hy1 小时前
斯特林数:组合划分的递归经典,一二两类全解
python·算法·斯特林数
青春:一叶知秋2 小时前
【Python】python基本语法和使用
开发语言·python