繁体   English   中英

如何用空格替换标点符号 python

[英]How to replace punctuation with space python

我使用此代码从sentence中删除punctuation ,但现在我需要用space替换punctuation

sentence = 'hi,how are you?'
temp = ''.join([''.join(c for c in s if c not in string.punctuation) for s in sentence])

outPut => `hihow are you`

我需要这样

outPut => `hi how are you`

我需要最快的方法来做到这一点

您可以使用条件表达式来调整您的生成器理解:

import string

sentence = 'hi,how are you?'
temp = ''.join(c if c not in string.punctuation else ' ' for c in sentence)
print(temp) # hi how are you

您可以在这里使用正则表达式方法:

import string
import re

sentence = 'hi,how are you?'
output = re.sub(r'[' + string.punctuation + r']+', ' ', sentence).strip()
print(output)  # hi how are you

Python 内置 function 用于更换。

sentence = 'The.quick.brown.fox.jumps.over.the.lazy.dog'

print(sentence.replace('.',' '))

您可以使用 package re中的sub方法进行全面替换:

import string 

re.sub(f'[{string.punctuation}]+', " ", s)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM