使用Python删除标点符号/符号,除了句点,逗号

时间:2016-10-09 17:49:52

标签: python normalization

在Python中,我需要从列表中删除几乎所有标点符号,但保存句点和逗号。我应该创建一个函数来执行此操作还是变量?基本上我想删除除字母以外的所有符号(我已将大写字母转换为小写)和句点和逗号(也可能是撇号)。

#Clean tokens up (remove symbols except ',' and '.')

def depunctuate()
   clean_tokens = []

   for i in lc_tokens:
       if (i not in [a-z.,])
       ...

2 个答案:

答案 0 :(得分:2)

您可以从string.punctuation构建一组不需要的标点符号 - 它提供包含标点符号的字符串,然后使用列表理解过滤掉集合中包含的字母:

import string

to_delete = set(string.punctuation) - {'.', ','} # remove comma and fullstop
clean_tokens = [x for x in lc_tokens if x not in to_delete]

答案 1 :(得分:0)

def palindrome(n):
    start = 0
    end = len(n) - 1
    while (start < end):
        if (n[start] != n[end]):
            return False
        start = start + 1
        end = end - 1
    return True