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)
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)
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |