正则表达式连接由空格和连字符分隔的单词

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)

快速、非正则表达式的方法是

''.join(map(lambda s: s.strip(), s.split('-'))).split()

在连字符上拆分,去掉额外的白色space,重新加入字符串并在 space 上拆分,但这不会分隔点或问号。

这是一种方法:

[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?']

这里有两个操作:

  1. 根据空格拆分文本 不带连字符 同时使用否定前瞻和否定回顾。

  2. 在每个拆分词中,将前面或后面可能有空格的连字符替换为空字符串。

您可以在这里看到第一个操作的演示: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', '?']

这个问题还拆分了非字母、非空格而不是 hyphens/apostrophe。 if i 是必需的,因为拆分可能 return 一些 None 项。

这个怎么样:

>>> 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', '?']

上面使用了一个简单的space ' ',但是使用\s更好:

list(map(lambda x:re.sub('\s*-\s*','',x), filter(lambda x:x, re.split(r'(?<!-)\s+(?!-)|([.?])',s))))

(?<!-)\s+(?!-)表示space前后没有-
[.?] 表示单个 .?

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 以删除 space 和 - 在每个单词里面。