25

我需要使用正则表达式去除单词开头结尾的标点符号。似乎正则表达式将是最好的选择。我不希望从诸如“you're”之类的词中删除标点符号,这就是我不使用 .replace() 的原因。

4

4 回答 4

63

您不需要正则表达式来执行此任务。str.strip与 一起使用string.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"
于 2013-08-25T12:49:37.787 回答
2

我认为这个功能在删除标点符号方面会很有帮助和简洁:

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
于 2018-12-11T09:10:27.140 回答
1

如果你坚持使用 Regex,我推荐这个解决方案:

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
于 2021-05-31T12:55:39.877 回答
-3

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

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)

PS - 根据需要正确进行识别。希望这可以帮助!!

于 2018-06-22T10:12:20.243 回答