繁体   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