首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Python语言中的string.punctuation后面添加空格?

如何在Python语言中的string.punctuation后面添加空格?
EN

Stack Overflow用户
提问于 2016-12-07 18:31:11
回答 1查看 356关注 0票数 0

我想清理我的评论数据。下面是我的代码:

代码语言:javascript
复制
def processData(data):
    data = data.lower() #casefold    
    data = re.sub('<[^>]*>',' ',data) #remove any html     

    data = re.sub(r'#([^\s]+)', r'\1', data) #Replace #word with word
    remove = string.punctuation
    remove = remove.replace("'", "") # don't remove '
    p = r"[{}]".format(remove) #create the pattern
    data = re.sub(p, "", data)

    data = re.sub('[\s]+', ' ', data) #remove additional whitespaces

    pp = re.compile(r"(.)\1{1,}", re.DOTALL) #pattern for remove repetitions 
    data = pp.sub(r"\1\1", data)

    return data

这段代码几乎工作得很好,但仍然存在一个问题。对于“她在公共服务部门工作”这句话,

我拿到了“她在公共服务部门工作”。

问题是字符串标点后没有空格。

我希望我的句子是这样的:“她从事公共服务”。

你能帮我写代码吗?

EN

回答 1

Stack Overflow用户

发布于 2016-12-07 18:51:51

我想你想要的是:

代码语言:javascript
复制
>>> st = 'she works in public-service'
>>> import re
>>> re.sub(r'([{}])'.format(string.punctuation),r' ',st)
'she works in public service'
>>> 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41015075

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档