使用maketrans/trans从包含字符串的序列中删除标点

2024-10-02 04:30:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想删除一系列字符串中的标点符号。你知道吗

我使用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:< >- Flavors:< >- Decoration Type:< >- Icing:< >-

这是我的密码:

remove_punc = str.maketrans(' ', ' ', string.punctuation)
df.Summary = df.Summary.str.translate(remove_punc)
df.Description = df.Description.str.translate(remove_punc)

代码后面的句子:

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,似乎代码没有用空格替换-。而在第二个场景中,它似乎用空格代替了标点符号。你知道吗

我没有包含在上面的代码片段中,但是我也将所有的句子都小写了。你知道吗

关于为什么会发生这种情况有什么建议吗?你知道吗

谢谢


Tags: of代码dfwillremovetranslatecaketake
2条回答

在第二句中不是用空格代替。原始字符串中的标点符号字符之间有空格,这些字符只是被保留了下来。你知道吗

请参阅https://docs.python.org/3/library/stdtypes.html#str.maketrans以获取有关如何工作的详细信息。你知道吗

如果要用空格替换每个标点字符:

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     

这里对其他方法有一个很好的概述: Fast punctuation removal with pandas

相关问题 更多 >

    热门问题