Skip to main content
 首页 » 编程设计

python之这是在 python 中修剪标点符号的正确/有效方法吗

2025年05月04日11sharpest

我有一个非常大的文件集,我正在迭代这些文件以计算所有单词。我正在计算的单词中可以包含标点符号,例如“hyper-speed”或“12:30”,但如果标点符号位于单词的末尾,则应将其删除。示例(“吓人!”=>“吓人”,“rip-”=>“rip”)。这是我的算法。传递给此函数的所有内容均为小写。

def cleanWord(word): 
   if len(word) <= 2: 
        return word 
    if word[0] in string.punctuation: 
        return cleanWord(word[1:]) 
    if word[-1] in string.punctuation: 
        return cleanWord(word[:-2]) 
    return word 

有时单词在我的计数中被以尴尬的方式修剪(例如“philidelphi”或“organiz”),我想知道这是因为在如此大的数据集中存在一些拼写错误还是我的算法有缺陷?

请您参考如下方法:

>>> from string import punctuation 
>>> word = "-scary!" 
>>> word.strip(punctuation) 
'scary' 

正如@hughdbrown 指出的那样,还有 lstrip 和 rstrip 替代方案,它们分别只从左侧和右侧剥离。