请求开发Python代码实现店铺名称自动分类功能
Python实现店铺名称自动分类
核心思路
通过关键词匹配实现分类:预先定义店铺类别与对应关键词的映射关系,将输入的店铺名称转为小写后遍历匹配关键词,返回对应类别;无匹配项时返回默认类别(如"Other")。
代码实现
def classify_store(store_name): # 定义类别-关键词映射,可根据需求扩展 category_mapping = { 'chemist': ['medical', 'pharmacy', 'chemist'], 'restaurant': ['restaurant', 'cafe', 'diner', 'bistro'], 'General store': ['general store'] # 可添加更多类别及对应关键词 } # 统一转为小写,避免大小写干扰匹配 lower_name = store_name.lower() # 遍历映射匹配关键词 for category, keywords in category_mapping.items(): for keyword in keywords: if keyword in lower_name: return category # 无匹配项返回默认类别 return 'Other'
测试示例
# 测试给定案例 print(classify_store("Anand Medical store")) # 输出: chemist print(classify_store("7 General store")) # 输出: General store # 扩展测试用例 print(classify_store("Downtown Bistro")) # 输出: restaurant print(classify_store("City Pharmacy")) # 输出: chemist print(classify_store("Lucky Grocery")) # 输出: Other
优化建议
- 若需避免部分词误匹配(比如"medical"出现在非药店名称中),可改为整词匹配:用
split()分割名称后,检查关键词是否在分割后的词列表里。 - 针对特殊写法或变体词,可引入正则表达式做模糊匹配。
- 分类规则较多时,可将映射关系存入JSON配置文件,便于后续维护和扩展。
内容的提问来源于stack exchange,提问作者mansi sharma
相关产品推荐
相关产品推荐

