基于Pandas的SMS缩写文本扩展功能实现技术问询
替换文本中的SMS缩写(基于Excel映射表)
你已经搭好了基础框架,我来帮你完善这个功能,实现从Excel读取缩写映射表,精准替换文本中的SMS缩写:
完整实现代码
import re import pandas as pd # 读取存储缩写与完整表达的Excel文件 sdf = pd.read_excel('expansion.xlsx') # 将Excel中的两列转换为替换字典:键是缩写,值是对应的完整表达 rep_dict = dict(zip(sdf['word'], sdf['expansion'])) # 构建正则匹配模式:确保只匹配作为独立单词的缩写,避免部分匹配错误 # 用re.escape处理缩写中的特殊字符,保证正则语法正确 pattern = re.compile(r'\b(' + '|'.join(re.escape(key) for key in rep_dict.keys()) + r')\b') # 待处理的示例文本 input_text = "fyi gtg gtg2 fyii really need to wrap up this work, brb soon!" # 定义替换逻辑:匹配到缩写就返回对应的完整表达,否则返回原内容 def replace_abbreviation(match_obj): return rep_dict[match_obj.group(0)] # 执行替换操作 output_text = pattern.sub(replace_abbreviation, input_text) # 打印结果 print(output_text)
关键细节解释
- 精准匹配:使用正则表达式的
\b(单词边界)确保只替换独立存在的缩写,比如不会把gtg在gtg123这种字符串中误替换。 - 安全转义:
re.escape(key)会自动处理缩写中的特殊字符(如果有的话),避免正则表达式语法错误。 - 映射表灵活性:所有缩写和对应表达都存在Excel里,后续新增或修改缩写不需要改代码,直接更新Excel即可。
测试结果
运行上述代码后,示例文本会被转换为:
for your information got to go got to go too sample test really need to wrap up this work, be right back soon!
可选优化:忽略大小写匹配
如果需要支持大小写不敏感的替换(比如匹配FYI、Gtg这类变体),可以修改正则模式和替换逻辑:
# 构建忽略大小写的正则模式 pattern_case_insensitive = re.compile( r'\b(' + '|'.join(re.escape(key) for key in rep_dict.keys()) + r')\b', flags=re.IGNORECASE ) # 将替换字典的键转为小写,方便匹配 rep_dict_lower = {key.lower(): value for key, value in rep_dict.items()} def replace_abbreviation_case_insensitive(match_obj): matched_key = match_obj.group(0).lower() return rep_dict_lower.get(matched_key, match_obj.group(0)) # 执行大小写不敏感的替换 output_text_case_insensitive = pattern_case_insensitive.sub(replace_abbreviation_case_insensitive, input_text)
内容的提问来源于stack exchange,提问作者Programmer_nltk




