我有一个非常大的文件集,我正在迭代计算所有的单词.我正在计算的单词可以在其中加上标点符号,例如"超高速"或"12:30",但如果标点符号位于单词的末尾,则应对其进行修剪.示例("scary!"=>"scary","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
Run Code Online (Sandbox Code Playgroud)
有时在我的计数中用尴尬的方式(例如"philidelphi"或"组织")修剪单词,我想知道这是因为在这么大的数据集中有一些错误拼写或我的算法是否有缺陷?
>>> from string import punctuation
>>> word = "-scary!"
>>> word.strip(punctuation)
'scary'
Run Code Online (Sandbox Code Playgroud)
正如@hughdbrown指出的那样,也存在lstrip和rstrip替代只从左侧剥离和右.
| 归档时间: |
|
| 查看次数: |
189 次 |
| 最近记录: |