使用正则表达式去除Python中的标点符号

28

我需要使用正则表达式来去掉单词开头和结尾的标点符号。正则表达式似乎是这个问题的最佳解决方案。我不想从像 “you're” 这样的单词中移除标点符号,这就是为什么我不使用 .replace() 的原因。


1
对于那些想要在使用Python 3.x时区分Unicode字母数字字符和其他所有字符的人,您可以在正则表达式中使用\w和\W。这帮助我编写了Tkinter文本小部件中的Control-Shift-Left/Right功能(跳过单词前的所有标点符号等内容)。在找到解决方案之前,我先看到了您的帖子。因此,我认为它可能会帮助到处于类似困境的人。 - Brōtsyorfuzthrāx
4个回答

71

你不需要正则表达式来完成这个任务。使用str.stripstring.punctuation

>>> import string
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> '!Hello.'.strip(string.punctuation)
'Hello'

>>> ' '.join(word.strip(string.punctuation) for word in "Hello, world. I'm a boy, you're a girl.".split())
"Hello world I'm a boy you're a girl"

2
纯属好奇,这个正则表达式的方法会是什么? - Anmol Singh Jaggi
re.sub('\S+', lambda m: re.sub('^\W+|\W+$', '', m.group()), '...')。注意:您需要精确替换\W,因为它将排除“_”(如果您将“_”视为标点符号)。演示:http://ideone.com/Ti44Bw - falsetru
好的,但它们是否等价? - Anmol Singh Jaggi
1
@ArthurKhazbs,正则表达式的解决方案在评论中。 :) - falsetru
1
因为提到了string.punctuation,我点了个赞,我之前不知道它的存在! - Stephen
显示剩余4条评论

4

我认为这个函数可以帮助我们简明地去除标点符号:

import re
def remove_punct(text):
    new_words = []
    for word in text:
        w = re.sub(r'[^\w\s]','',word) #remove everything except words and space
        w = re.sub(r'_','',w) #how to remove underscore as well
        new_words.append(w)
    return new_words

1
请注意,您可以使用w = re.sub(r'([^\w\s]|_)','',word)来进一步简化您的条件。 - Stephen

3
如果您坚持使用正则表达式,我建议采用以下解决方案:
import re
import string
p = re.compile("[" + re.escape(string.punctuation) + "]")
print(p.sub("", "\"hello world!\", he's told me."))
### hello world hes told me

请注意,您可以传递自己的标点符号:
my_punct = ['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '.',
           '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', 
           '`', '{', '|', '}', '~', '»', '«', '“', '”']

punct_pattern = re.compile("[" + re.escape("".join(my_punct)) + "]")
re.sub(punct_pattern, "", "I've been vaccinated against *covid-19*!") # the "-" symbol should remain
### Ive been vaccinated against covid-19

这不符合OP的要求,即保留单词中的标点符号,例如"he's"和"I've"。 - elAndrez3000

-4

您可以使用正则表达式从文本文件或特定字符串文件中删除标点符号,方法如下 -

new_data=[]
with open('/home/rahul/align.txt','r') as f:
    f1 = f.read()
    f2 = f1.split()



    all_words = f2 
    punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' 
    # You can add and remove punctuations as per your choice 
    #removing stop words in hungarian text and  english text and 
    #display the unpunctuated string
    # To remove from a string, replace new_data with new_str 
    # new_str = "My name$#@ is . rahul -~"

    for word in all_words: 
        if word not in punctuations:
           new_data.append(word)

    print (new_data)

附言:请按照要求正确缩进。 希望这能帮到你!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接