Python 如何删除单词或数字中间的标点符号?

Python 如何删除单词或数字中间的标点符号?,python,punctuation,Python,Punctuation,例如,如果我有一个数字串和一个单词列表: My_number = ("5,6!7,8") My_word =["hel?llo","intro"] 假设你想让我的号码变成一个字符串 >>> from string import punctuation >>> my_number = "5,6!7,8" >>> my_word = ["hel?llo", "intro"] >>> remove_punctuation = l

例如,如果我有一个数字串和一个单词列表:

My_number = ("5,6!7,8")
My_word =["hel?llo","intro"]
假设你想让我的号码变成一个字符串

>>> from string import punctuation
>>> my_number = "5,6!7,8"
>>> my_word = ["hel?llo", "intro"]
>>> remove_punctuation = lambda s: s.translate(None, punctuation)
>>> my_number = remove_punctuation(my_number)
>>> my_word = map(remove_punctuation, my_word)
>>> my_number
'5678'
>>> my_word
['helllo', 'intro']
假设你想让我的号码变成一个字符串

>>> from string import punctuation
>>> my_number = "5,6!7,8"
>>> my_word = ["hel?llo", "intro"]
>>> remove_punctuation = lambda s: s.translate(None, punctuation)
>>> my_number = remove_punctuation(my_number)
>>> my_word = map(remove_punctuation, my_word)
>>> my_number
'5678'
>>> my_word
['helllo', 'intro']
使用str.translate:

使用正则表达式:

使用列表理解和str.join:

功能:

>>> from collections import Iterable
def my_strip(args):
    if isinstance(args, Iterable) and not isinstance(args, basestring):
        return [ x.translate(None, punctuation) for x in args]
    else:
        return args.translate(None, punctuation)
...     
>>> my_strip("5,6!7,8")
'5678'
>>> my_strip(["hel?llo","intro"])
['helllo', 'intro']
使用str.translate:

使用正则表达式:

使用列表理解和str.join:

功能:

>>> from collections import Iterable
def my_strip(args):
    if isinstance(args, Iterable) and not isinstance(args, basestring):
        return [ x.translate(None, punctuation) for x in args]
    else:
        return args.translate(None, punctuation)
...     
>>> my_strip("5,6!7,8")
'5678'
>>> my_strip(["hel?llo","intro"])
['helllo', 'intro']
使用+:


这只适用于python2。在python3中,filter将始终返回一个iterable,您必须执行以下操作。joinfilterstr.isalnum,使用+:


这只适用于python2。在python3中,filter将始终返回一个iterable,您必须执行.joinfilterstr.isalnum,这是一个支持Unicode的解决方案。Po是标点符号的Unicode类别

>>> import unicodedata
>>> mystr = "1?2,3!abc"
>>> mystr = "".join([x for x in mystr if unicodedata.category(x) != "Po"])
>>> mystr
'123abc'

您也可以使用正则表达式,使用re模块和re.sub。遗憾的是,标准库regex模块不支持Unicode类别,因此您必须指定要手动删除的所有字符。有一个单独的库称为regex,它有这样一个特性,但它是非标准的

这是一个支持Unicode的解决方案。Po是标点符号的Unicode类别

>>> import unicodedata
>>> mystr = "1?2,3!abc"
>>> mystr = "".join([x for x in mystr if unicodedata.category(x) != "Po"])
>>> mystr
'123abc'

您也可以使用正则表达式,使用re模块和re.sub。遗憾的是,标准库regex模块不支持Unicode类别,因此您必须指定要手动删除的所有字符。有一个单独的库称为regex,它有这样一个特性,但它是非标准的

My_number不是元组,它是字符串。My_number不是元组,它是字符串。这仅适用于python2。在python3中,筛选器将始终返回一个iterable,您必须这样做。joinfilterstr.isalnum,_文本。@Bakuriu,谢谢您的建议。我在答案中包含了你的评论。这只适用于python2。在python3中,筛选器将始终返回一个iterable,您必须这样做。joinfilterstr.isalnum,_文本。@Bakuriu,谢谢您的建议。我在回答中包括了你的评论。
>>> import unicodedata
>>> mystr = "1?2,3!abc"
>>> mystr = "".join([x for x in mystr if unicodedata.category(x) != "Po"])
>>> mystr
'123abc'