You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数中如何移除标点?str.maketrans方案可行性及插入位置咨询

问题1:str.maketrans('', '', string.punctuation)方案是否可行?

  • 该方案完全可行。str.maketrans的第三个参数可直接指定需要从字符串中删除的字符集合,string.punctuation内置了所有标准英文ASCII标点符号,完全匹配你的示例英文场景需求。
  • 小提示:如果后续需要处理中文等非英文标点,该方案不适用,自行补充对应的标点字符集即可适配。

问题2:代码写入位置

你需要把标点移除逻辑放在列表拼接为字符串之后、分割为单词列表之前的位置,也就是" ".join(lst)执行完成后,调用str.translate()方法传入生成的删除映射表即可。

修改后的完整可运行代码如下:

import string

def convert(lst):
    # 生成标点删除映射表
    remove_punct_map = str.maketrans('', '', string.punctuation)
    # 拼接字符串后先移除标点,再分割为单词列表
    return " ".join(lst).translate(remove_punct_map).split()

lst = ["Good for the price, but poor Bluetooth connections."]
print(convert(lst))    

运行输出结果为:['Good', 'for', 'the', 'price', 'but', 'poor', 'Bluetooth', 'connections'],原字符串中的逗号、句号已被正常移除。

内容的提问来源于stack exchange,提问作者Asbjørn Vattøy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 16:15:05