我需要使用正则表达式来去掉单词开头和结尾的标点符号。正则表达式似乎是这个问题的最佳解决方案。我不想从像 “you're” 这样的单词中移除标点符号,这就是为什么我不使用 .replace() 的原因。
我需要使用正则表达式来去掉单词开头和结尾的标点符号。正则表达式似乎是这个问题的最佳解决方案。我不想从像 “you're” 这样的单词中移除标点符号,这就是为什么我不使用 .replace() 的原因。
你不需要正则表达式来完成这个任务。使用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"
string.punctuation
,我点了个赞,我之前不知道它的存在! - Stephen我认为这个函数可以帮助我们简明地去除标点符号:
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
w = re.sub(r'([^\w\s]|_)','',word)
来进一步简化您的条件。 - Stephenimport 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
您可以使用正则表达式从文本文件或特定字符串文件中删除标点符号,方法如下 -
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)
附言:请按照要求正确缩进。 希望这能帮到你!