簡體   English   中英

如何去除Python中的標點符號而不留空格

[英]How to remove punctuation in Python without leaving a space

我想從文本中刪除某些標點符號。 我能夠刪除我想要的字符,但它會留下一個空格而不是字符。

In { ) other news tonight,
a Constitutional { | / !! amendment

我有一個像上面這樣的文本,當我處理它時它變成了

In   other news tonight,
a Constitutional    !! amendment

代替

In other news tonight,
a Constitutional !! amendment

下面是我的代碼

for line in lines:
    exclude = set('"#$%&\()*+-/:<=>@[\\]^_`{|}')
    line = ''.join(ch for ch in line if ch not in exclude)

如何刪除正在生成的空白區域?

沒有創建空白空間。 您的字符串在這些字符之間已經有空格。 刪除這些字符不會刪除它們之間的空格。 一種可能的解決方案是,我假設您要刪除任何具有多個連續空格的區域。 將您的代碼替換為:

exclude = set('"#$%&\()*+-/:<=>@[\\]^_`{|}')
for line in lines:
    line = ''.join(ch for ch in line if ch not in exclude)
    line = ' '.join(line.split())

這將刪除所有雙空格。

您可以使用str.split方法拆分字符串,以便將多個空格視為一個,然后通過空格將結果列表連接回一個字符串:

exclude = set('"#$%&\()*+-/:<=>@[\\]^_`{|}')
for line in lines:
    line = ' '.join(''.join(' ' if ch in exclude else ch for ch in line).split())

我想從文本中刪除某些標點符號。 我能夠刪除我想要的字符,但它一直留下一個空格而不是字符。

In { ) other news tonight,
a Constitutional { | / !! amendment

我有一個像上面這樣的文本,當我處理它時它變成

In   other news tonight,
a Constitutional    !! amendment

代替

In other news tonight,
a Constitutional !! amendment

下面是我的代碼

for line in lines:
    exclude = set('"#$%&\()*+-/:<=>@[\\]^_`{|}')
    line = ''.join(ch for ch in line if ch not in exclude)

如何刪除正在生成的空白空間?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM