我想删除文本中的某些标点符号。我可以删除我想要的字符,但它总是留下一个空格,而不是字符。
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)如何删除正在生成的空格?
发布于 2020-04-03 03:23:58
未创建任何空白空间。您的字符串在这些字符之间已有空格。删除这些字符不会删除它们之间的空格。一种可能的解决方案是,我假设您想要删除具有多个连续空间的任何区域。将您的代码替换为:
exclude = set('"#$%&\()*+-/:<=>@[\\]^_`{|}')
for line in lines:
line = ''.join(ch for ch in line if ch not in exclude)
line = ' '.join(line.split())这将删除所有的双空格。
发布于 2020-04-03 03:24:04
您可以使用str.split方法拆分字符串,以便将多个空格视为一个空格,然后使用空格将结果列表重新合并为一个字符串:
exclude = set('"#$%&\()*+-/:<=>@[\\]^_`{|}')
for line in lines:
line = ' '.join(''.join(' ' if ch in exclude else ch for ch in line).split())https://stackoverflow.com/questions/60999370
复制相似问题