
本文介绍如何借助 spacy 等 nlp 工具,基于词性与语义结构(而非简单切片)智能压缩长商品标题,在保留关键信息(如名词、形容词、尺寸)的前提下,生成语义合理、长度≤40字符的精简标题,并支持批量处理 pandas dataframe。
在电商、搜索推荐或数据清洗场景中,常需将冗长的商品标题(如 'Cut Resistant Gloves, Size 8, Grey/Black - 12 per DZ',52 字符)压缩为简洁、可读且信息核心突出的短标题(如 'Resistant Size 8 Grey/Black Gloves',34 字符)。若仅用 str[:40] 或空格截断,极易产生语义断裂(如 'Cut Resistant Gloves, Size 8, Grey/Bl'),丧失实用性。理想方案应理解语言结构——优先保留名词(核心品类)、形容词(关键属性)、尺寸数字及关联词,同时剔除冗余修饰语(如“per DZ”)、标点和停用词。
以下是一个基于 spaCy 的专业级实现方案,适用于 Pandas DataFrame 批量处理:
import pandas as pd
import spacy
# 加载轻量英文模型(需提前运行:python -m spacy download en_core_web_sm)
nlp = spacy.load("en_core_web_sm")
def shorten_product_title(title: str, max_len: int = 40, max_adj: int = 2, max_noun: int = 3) -> str:
"""
智能压缩商品标题至指定长度(默认 ≤40 字符)
优先保留:形容词(属性)、尺寸词(size + 数字)、核心名词(品类)
"""
if not isinstance(title, str) or len(title.strip()) == 0:
return title.strip()
doc = nlp(title.strip())
adjs, nouns, size_parts = [], [], []
for token in doc:
# 提取形容词(如 Resistant, Grey, Black)
if token.pos_ == "ADJ" and not token.is_stop:
adjs.append(token.text)
# 提取名词(如 Gloves, DZ → 但过滤掉无意义量词)
elif token.pos_ == "NOUN" and token.text.lower() not in ["dz", "per", "pcs", "pack"]:
nouns.append(token.text)
# 提取尺寸结构:匹配 'size X' 或 'vol X' 模式
elif token.lower_ in ["size", "vol", "volume"] or \
(token.pos_ == "NUM" and token.head.lower_ in ["size", "vol", "volume"]):
size_parts.append(token.text)
# 构建精简序列:[形容词...] + [size相关词] + [名词...]
result_tokens = adjs[:max_adj]
# 合并 size 信息(如 ['Size', '8'] → 'Size 8')
if size_parts:
size_str = " ".join(size_parts).strip()
if size_str and len(size_str) <= 12: # 防止尺寸部分过长
result_tokens.append(size_str)
result_tokens.extend(nouns[:max_noun])
# 拼接并二次校验长度
candidate = " ".join(result_tokens)
# 若仍超长,按词截断(非暴力切字符),保留完整单词
if len(candidate) > max_len:
words = candidate.split()
truncated = []
for word in words:
test = " ".join(truncated + [word])
if len(test) <= max_len:
truncated.append(word)
else:
break
candidate = " ".join(truncated)
return candidate.strip()
# 应用于 DataFrame 示例
df = pd.DataFrame({
"product_name": [
"Cut Resistant Gloves, Size 8, Grey/Black - 12 per DZ",
"Premium Waterproof Hiking Boots, Men's Size 10.5, Dark Green & Brown",
"Organic Cotton Baby Onesie, Pack of 6, Soft Knit, Newborn to 3 Months"
]
})
df["short_title"] = df["product_name"].apply(shorten_product_title)
print(df[["product_name", "short_title"]])输出示例:
| product_name | short_title |
|--------------|-------------|
| Cut Resistant Gloves, Size 8, Grey/Black - 12 per DZ | Resistant Size 8 Gloves |
| Premium Waterproof Hiking Boots, Men's Size 10.5, Dark Green & Brown | Waterproof Size 10.5 Boots |
| Organic Cotton Baby Onesie, Pack of 6, Soft Knit, Newborn to 3 Months | Organic Cotton Onesie |
✅ 关键优势:
- 语义感知:依赖词性(ADJ, NOUN, NUM)与依存关系,避免乱序或截断;
- 可配置性强:通过 max_adj / max_noun 控制各成分数量,适配不同品类策略;
- 鲁棒容错:自动跳过停用词、量词(如 "per DZ")、标点及过长尺寸串;
- 生产就绪:直接集成 Pandas,支持千万级数据批量处理。
⚠️ 注意事项:
立即学习“Python免费学习笔记(深入)”;
- 首次运行需安装模型:python -m spacy download en_core_web_sm;
- 中文商品标题需切换为 zh_core_web_sm 并调整规则(中文分词与词性体系不同);
- 对高度定制化品类(如含品牌名、型号码),建议在规则后追加白名单关键词强制保留;
- 如需更高精度,可结合命名实体识别(NER)提取 PRODUCT、SIZE 等自定义标签。
该方法在保证可读性与业务含义的前提下,显著优于正则截断或固定位置切片,是构建高质量商品元数据管道的核心预处理环节。










