【发布时间】:2020-08-27 15:15:10
【问题描述】:
我正在尝试输出字符串列表中每个单词的列表。以下代码有效,但它没有将“i”作为一个词捕获?我真的很挣扎正则表达式,非常感谢任何帮助!
example = ["hi one don't 42 i i",'hello world','foo bar i']
word_list = []
for words in list(example):
rgx = re.compile("([\w][\w']*\w)")
word_list += rgx.findall(words)
word_list
输出
['hi', 'one', "don't", '42', 'hello', 'world', 'foo', 'bar']
【问题讨论】:
-
试试
\b(\w+(?:[']\w+)*)\b,但比那个更复杂 -
@Edward 似乎不起作用,不过感谢您的尝试!
-
我尝试但工作。想反正。 >>> print ( re.compile(r"\b(\w+(?:[']\w+)*)\b").findall("hi one don't 42 ii hello world foo bar i") )
['hi', 'one', "don't", '42', 'i', 'i', 'hello', 'world', 'foo', 'bar', 'i']