【问题标题】:How to find words in a list of strings using regex in python如何在python中使用正则表达式在字符串列表中查找单词
【发布时间】: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']

标签: python regex string list


【解决方案1】:

如果你想要all所有句子中的单词,你可以使用嵌套列表推导,使用str.split查找列表中每个句子中的所有单词:

example = ["hi one don't 42 i i",'hello world','foo bar i']
words = [word for sentence in example for word in sentence.split()]
print(words)

输出:

['hi', 'one', "don't", '42', 'i', 'i', 'hello', 'world', 'foo', 'bar', 'i']

【讨论】:

    【解决方案2】:

    您只需使用split() 即可做到这一点。

    无需使用正则表达式从字符串列表中提取单词:

    word_list = []
    
    for words in example:
        words = words.split()
        for word in words:
            word_list.append(word)
    
    print(word_list)
    

    输出:

    ['hi', 'one', "don't", '42', 'i', 'i', 'hello', 'world', 'foo', 'bar', 'i']
    

    【讨论】:

    • 这只会返回不是我想要的唯一项目。不过,我真的很感谢您的意见!
    • 如果您不想要唯一的单词,只需使用 list 而不是 set ()。而已。我以为你只是想要文字,所以重复没有意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 2019-02-20
    • 2012-12-04
    • 1970-01-01
    相关资源
    最近更新 更多