Python 使用maketrans/translate从包含字符串的序列中删除标点
我想删除序列中字符串的标点符号 我正在使用python3.6和maketrans,translate函数来实现这一点。然而,它并没有给我想要的结果 代码前有两句话:Python 使用maketrans/translate从包含字符串的序列中删除标点,python,string,pandas,series,Python,String,Pandas,Series,我想删除序列中字符串的标点符号 我正在使用python3.6和maketrans,translate函数来实现这一点。然而,它并没有给我想要的结果 代码前有两句话: Baking cake of straw-bana-choco will take longer than expcted Please include as much of the following data that is available.< >< >- Cake Type:< >-
Baking cake of straw-bana-choco will take longer than expcted
Please include as much of the following data that is available.< >< >- Cake Type:< >- Flavors:< >- Decoration Type:< >- Icing:< >-
代码后面的句子:
baking cake of strawbanachoco will take longer than expcted
please include as much of the following data that is available cake type flavors decoration type icing
所以我想知道为什么strawbanachoco不是staw bana choco,似乎代码没有用空格代替-。而在第二种情况下,它似乎是用空格代替标点符号
我没有在上面的代码片段中包含,但我也将所有句子都小写
有没有关于为什么会发生这种情况的建议
谢谢第二句中没有空格代替。原始字符串中的标点符号字符之间有空格,这些字符只是被保留了下来
有关此操作的详细信息,请参阅。如果要将每个标点符号替换为空格:
s = """
Baking cake of straw-bana-choco will take longer than expcted
Please include as much of the following data that is available.< >< >- Cake Type:< >- Flavors:< >- Decoration Type:< >- Icing:< >-
"""
remove_punc = str.maketrans(dict.fromkeys(string.punctuation, ' '))
print(str.translate(s, remove_punc))
这里对其他方法有一个很好的概述:
因此,您要替换的字符只有和-?我要替换序列中可能出现的任何标点符号。那么以下任何一项:!$%&\'*+,-./:@[\]^_`{|}~
s = """
Baking cake of straw-bana-choco will take longer than expcted
Please include as much of the following data that is available.< >< >- Cake Type:< >- Flavors:< >- Decoration Type:< >- Icing:< >-
"""
remove_punc = str.maketrans(dict.fromkeys(string.punctuation, ' '))
print(str.translate(s, remove_punc))
Baking cake of straw bana choco will take longer than expcted
Please include as much of the following data that is available Cake Type Flavors Decoration Type Icing