簡體   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