Python-从文本中删除一些标点符号
我希望Python只删除字符串中的一些标点符号,比如说,我希望删除除“@”之外的所有标点符号Python-从文本中删除一些标点符号,python,Python,我希望Python只删除字符串中的一些标点符号,比如说,我希望删除除“@”之外的所有标点符号 import string remove = dict.fromkeys(map(ord, '\n ' + string.punctuation)) sample = 'The quick brown fox, like, totally jumped, @man!' sample.translate(remove) 这里是输出 The quick brown fox like totally jum
import string
remove = dict.fromkeys(map(ord, '\n ' + string.punctuation))
sample = 'The quick brown fox, like, totally jumped, @man!'
sample.translate(remove)
这里是输出
The quick brown fox like totally jumped man
但我想要的是这样的东西
The quick brown fox like totally jumped @man
有没有一种方法可以选择性地删除文本中的标点符号,而不保留我们希望在文本中保持完整的标点符号?包含所有标点符号。从中删除@。然后,在得到标点符号字符串时替换为
>>> import re
>>> a = string.punctuation.replace('@','')
>>> re.sub(r'[{}]'.format(a),'','The quick brown fox, like, totally jumped, @man!')
'The quick brown fox like totally jumped @man'
包含所有标点符号。从中删除@。然后,在得到标点符号字符串时替换为
>>> import re
>>> a = string.punctuation.replace('@','')
>>> re.sub(r'[{}]'.format(a),'','The quick brown fox, like, totally jumped, @man!')
'The quick brown fox like totally jumped @man'
只需从替换字符串中删除您不想触摸的字符:
import string
remove = dict.fromkeys(map(ord, '\n' + string.punctuation.replace('@','')))
sample = 'The quick brown fox, like, totally jumped, @man!'
sample.translate(remove)
还要注意,我将“\n”改为“\n”,因为前者将从字符串中删除空格
结果:
The quick brown fox like totally jumped @man
只需从替换字符串中删除您不想触摸的字符:
import string
remove = dict.fromkeys(map(ord, '\n' + string.punctuation.replace('@','')))
sample = 'The quick brown fox, like, totally jumped, @man!'
sample.translate(remove)
还要注意,我将“\n”改为“\n”,因为前者将从字符串中删除空格
结果:
The quick brown fox like totally jumped @man
我在这段代码的输出中没有看到任何空格。你确定这就是你得到的吗?我在这段代码的输出中没有看到任何空格。你确定这就是你得到的吗?正则表达式部分有什么用?正则表达式部分有什么用?