在Python中消除一系列.replace()调用

Rya*_*yan 2 python string syntax code-cleanup

我正在开发一个涉及解析文本页面的项目.我编写了以下函数来从单词中删除某些标点符号并将其转换为小写:

def format_word(word):
    return word.replace('.', '').replace(',', '').replace('\"', '').lower()
Run Code Online (Sandbox Code Playgroud)

有没有办法将.replace()的所有调用合并为一个?这看起来很丑陋!我能想到的唯一方法是:

def format_word(word):
    for punct in '.,\"':
        word.replace(punct, '')
    return word.lower()
Run Code Online (Sandbox Code Playgroud)

fal*_*tru 8

str.translate如果要删除字符,可以使用:

在python 2.x中:

>>> 'Hello, "world".'.translate(None, ',."')
'Hello world'
Run Code Online (Sandbox Code Playgroud)

在python 3.x中:

>>> 'Hello, "world".'.translate(dict.fromkeys(map(ord, ',."')))
'Hello world'
Run Code Online (Sandbox Code Playgroud)