首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用撇号解除字符串的标记后,删除空格

使用撇号解除字符串的标记后,删除空格
EN

Stack Overflow用户
提问于 2018-02-24 03:46:41
回答 2查看 621关注 0票数 0

我想通过regex或detokenizing来删除单词中的空格,比如can't或won't

代码语言:javascript
复制
from nltk.tokenize import WordPunctTokenizer
tok = WordPunctTokenizer()
detok = MosesDetokenizer()

pattern= "[^\w ]+ "
text= "i can ' t use this cause they won ' t fit"
string= re.sub(pattern, '', text)
tk = tok.tokenize(string)
output= detok.detokenize(tk, return_str = True)
print(output)

 "i can 't use this cause they won' t fit"

任何关于如何删除' can‘和'won’之后的空格的想法,这样我就可以拥有can't和When‘t了。当我使用output = (' '.join(tk)).strip()去标记化时,我得到了两个空格,一个在撇号前后。示例i can ' t use this cause they won ' t fit

EN

回答 2

Stack Overflow用户

发布于 2018-02-24 03:59:26

@BenT我不能说关于正则表达式,但是在你的输出中,你可以应用以下操作:

代码语言:javascript
复制
output = "i can 't use this cause they won' t fit"
output = "'".join(output.split(" '"))
output = "'".join(output.split("' "))
print(output)
"i can't use this cause they won't fit"

这里也有一行解决方案:

代码语言:javascript
复制
output = output.replace("' ", "'").replace(" '", "'")
print(output)
"i can't use this cause they won't fit"
票数 0
EN

Stack Overflow用户

发布于 2018-02-24 04:36:49

我认为你可以简单地做一些事情,比如:

代码语言:javascript
复制
output = "i can 't use this cause they won' t fit"
output = output.replace(" '", "")
print output
"i can't use this cause they won't fit"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48955218

复制
相关文章

相似问题

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