用正则表达式去除标点符号 - python [英] strip punctuation with regex - python

查看:45
本文介绍了用正则表达式去除标点符号 - python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用正则表达式在单词的 startend 处去除标点符号.似乎正则表达式将是最好的选择.我不想从你是"这样的词中删除标点符号,这就是我不使用 .replace() 的原因.

解决方案

您不需要正则表达式来执行此任务.使用 str.stripstring.punctuation:

<预><代码>>>>导入字符串>>>字符串.标点符号'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'>>>'!Hello.'.strip(string.punctuation)'你好'>>>' '.join(word.strip(string.punctuation) for word in "Hello, world. I'm a boy, you're a girl.".split())你好世界,我是男孩,你是女孩"

I need to use regex to strip punctuation at the start and end of a word. It seems like regex would be the best option for this. I don't want punctuation removed from words like 'you're', which is why I'm not using .replace().

解决方案

You don't need regular expression to do this task. Use str.strip with 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"

这篇关于用正则表达式去除标点符号 - python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆