【发布时间】:2019-06-21 14:00:14
【问题描述】:
我的字符串很乱,看起来像这样:
s="I'm hope-less and can -not solve this pro- blem on my own. Wo - uld you help me?"
我希望将连字符(有时是空格)剥离的单词放在一个列表中。期望的输出:
list = ['I'm','hopeless','and','cannot','solve','this','problem','on','my','own','.','Would','you','help','me','?']
我尝试了很多不同的变体,但都没有奏效..
rgx = re.compile("([\w][\w'][\w\-]*\w)")
s = "My string'"
rgx.findall(s)
【问题讨论】:
-
试试
r"\w+(?:'\w+)?|[^\s\w]+" -
谢谢,但这只能部分解决我的问题。 “问题”
-
啊,抱歉,我在手机上查看问题时错过了这一点。我认为您需要进行一些预处理,例如
re.sub(r'\b\s*-\s*\b', '', s),但由于正则表达式不“了解”英语,并且这显然会删除单词字符之间的连字符,因此可能会删除太多。 -
s=s.replace('-', '').replace('-', '').replace('-', '').replace('-','' ).replace(' ', ',').split(',')
标签: python regex python-3.x whitespace hyphen