【问题标题】:find out the words appeared in a paragraph找出段落中出现的单词
【发布时间】:2014-05-16 17:29:38
【问题描述】:
sentence = 'Alice was not a bit hurt, and she jumped up on to her feet in a moment.'
words = ['Alice','jumped','played']

我可以使用python中的filter函数来查找words中的所有元素,如sentence所示:

print filter(lambda x: x in words,sentence.split())

但是如果words中的元素中有空格,.split()函数就会出错:

words = ['Alice','jumped up','played']

在这种情况下,'jumped up'sentence 中找不到,这是不正确的。

有没有简单的方法可以解决问题(或许re包可以搞定?)

【问题讨论】:

    标签: python regex string python-2.7


    【解决方案1】:

    您可以为此使用正则表达式:

    In [71]: import re
    
    In [72]: words = ['Alice','jumped','played']
    
    In [73]: [w for w in words if re.search(r'\b{}\b'.format(re.escape(w)), sentence)]
    Out[73]: ['Alice', 'jumped']
    
    In [74]: words = ['Alice','jumped up','played']
    
    In [75]: [w for w in words if re.search(r'\b{}\b'.format(re.escape(w)), sentence)]
    Out[75]: ['Alice', 'jumped up']
    

    【讨论】:

    • +1 使用re.escape() 否则会一团糟。
    • 感谢您的意见。它完美地工作。但是你能解释一下 re.escape() 吗?我猜它的目的是处理字符串中的空间?但是 \b 也包括空间考虑..
    • @ChuNan re.escape 将转义任何被正则表达式视为特殊的字符,例如.* 等。
    • @Aशwiniचhaudhary 那么如果我不使用 re.escape 会发生什么?我在没有它的情况下尝试了您的代码,它返回所有空列表,表明不匹配。是不是因为一些'.'和 ' ' 字符包括在内?
    • @ChuNan 对于当前的单词列表,它可以正常工作,但如果您添加任何特殊符号,则它将无法正常工作。看看这个例子:ideone.com/KfLTfl
    猜你喜欢
    • 1970-01-01
    • 2017-05-24
    • 2018-04-09
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    相关资源
    最近更新 更多