![](/img/trans.png)
[英]Regex to match string which has words followed by whitespace then digits dot or hyphen and words followed by space and then (some info)
[英]Regex joining words splitted by whitespace and hyphen
我的字符串很乱,看起来像这样:
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)
这是一种方法:
[re.sub(r'\s*-\s*', '', i) for i in re.split(r'(?<!-)\s(?!-)', s)]
# ["I'm", 'hopeless', 'and', 'cannot', 'solve', 'this', 'problem', 'on', 'my', 'own.', 'Would', 'you', 'help', 'me?']
这里有两个操作:
使用负前瞻和负后瞻,基于没有连字符的空格拆分文本。
在每个拆分词中,将连字符前面或后面可能的空格替换为空字符串。
你可以在这里看到第一个操作的演示: https ://regex101.com/r/ayHPvY/2
第二个: https ://regex101.com/r/ayHPvY/1
编辑:要获得.
和?
也要分开,请改用:
[re.sub(r'\s*-\s*','', i) for i in re.split(r"(?<!-)\s(?!-)|([^\w\s'-]+)", s) if i]
# ["I'm", 'hopeless', 'and', 'cannot', 'solve', 'this', 'problem', 'on', 'my', 'own', '.', 'Would', 'you', 'help', 'me', '?']
问题还在于拆分非字母、非空格和连字符/撇号。 if i
是必要的,因为拆分可能会返回一些None
项目。
快速,非正则表达式的方法是
''.join(map(lambda s: s.strip(), s.split('-'))).split()
即在连字符上拆分,附加空白条带,重新加入字符串并在空格上拆分,但这不会分隔点或问号。
这个怎么样:
>>> s
"I'm hope-less and can -not solve this pro- blem on my own. Wo - uld you help me
?"
>>> list(map(lambda x:re.sub(' *- *','',x), filter(lambda x:x, re.split(r'(?<!-) +(?!-)|([.?])',s))))
["I'm", 'hopeless', 'and', 'cannot', 'solve', 'this', 'problem', 'on', 'my', 'own', '.', 'Would', 'you', 'help', 'me', '?']
上面使用了一个简单的空格' '
,但使用\s
更好:
list(map(lambda x:re.sub('\s*-\s*','',x), filter(lambda x:x, re.split(r'(?<!-)\s+(?!-)|([.?])',s))))
(?<!-)\s+(?!-)
表示没有-
之前或之后的空格。
[.?]
表示单.
还是?
.
re.split(r'(?<!-)\s+(?!-)|([.?])',s)
将相应地拆分字符串,但内部会有一些None
和空字符串''
:
["I'm", None, 'hope-less', None, 'and', None, 'can -not', None, 'solve', None, 'this', None, 'pro- blem', None, 'on', None, 'my', None, 'own', '.', '', None, 'Wo - uld', None, 'you', None, 'help', None, 'me', '?', '']
该结果直接馈送到filter
以删除None
和''
,然后馈送到map
以删除每个单词中的空格和-
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.