[英]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.