查找python中的字符串中是否存在单词

时间:2013-04-17 08:11:14

标签: python

以下是我需要帮助的代码段。

listword=["os","slow"]
sentence="photos"
if any(word in sentence for word in listword):
    print "yes"

它打印是,因为照片中存在操作系统。   但我想知道字符串中是否存在 os作为“word”存在而不是os 作为单词的一部分。是否有任何方式没有转换<强烈的>句子到单词列表。基本上我不希望程序打印yes.It必须打印yes只有当字符串包含os 单词

由于

5 个答案:

答案 0 :(得分:2)

您需要使用正则表达式,并在匹配时在每个单词周围添加\b个单词边界锚:

import re

if any(re.search(r'\b{}\b'.format(re.escape(word)), sentence) for word in listword):
    print 'yes'

\b边界锚点匹配字符串的起点和终点,以及字和非字字符之间的过渡(所以在空格和字母或数字之间,或标点符号和字母之间或数字)。

re.escape() function确保所有正则表达式元字符都被转义,并且我们匹配word的文字内容,并且不会意外地将其中的任何内容解释为表达式。

演示:

>>> listword = ['foo', 'bar', 'baz']
>>> sentence = 'The quick fox jumped over the barred door'
>>> if any(re.search(r'\b{}\b'.format(re.escape(word)), sentence) for word in listword):
...     print 'yes'
... 
>>> sentence = 'The tradition to use fake names like foo, bar or baz originated at MIT'
>>> if any(re.search(r'\b{}\b'.format(re.escape(word)), sentence) for word in listword):
...     print 'yes'
... 
yes

通过使用正则表达式,您现在也可以不区分大小写:

if any(re.search(r'\b{}\b'.format(re.escape(word)), sentence, re.I) for word in listword):
    print 'yes'

在此演示中,themit符合条件,即使句子中的情况不同:

>>> listword = ['the', 'mit']
>>> if any(re.search(r'\b{}\b'.format(re.escape(word)), sentence, re.I) for word in listword):
...     print 'yes'
... 
yes

答案 1 :(得分:1)

正如人们所指出的,您可以使用正则表达式将字符串拆分为列表字。这称为标记化。

如果正则表达式不能很好地适合你,那么我建议你看一下NTLK - 一个Python自然语言处理库。它包含各种各样的标记器,它们将根据空格,标点符号和其他功能来分割字符串,这些功能可能太难以使用正则表达式捕获。

示例:

>>> from nltk.tokenize import word_tokenize, wordpunct_tokenize, sent_tokenize
>>> s = '''Good muffins cost $3.88\nin New York.  Please buy me
... two of them.\n\nThanks.'''
>>> wordpunct_tokenize(s)
['Good', 'muffins', 'cost', '$', '3', '.', '88', 'in', 'New', 'York', '.',
'Please', 'buy', 'me', 'two', 'of', 'them', '.', 'Thanks', '.']
>>> "buy" in wordpunct_tokenize(s)
True

答案 2 :(得分:0)

这很简单,如果sentence字符串包含逗号,但仍然

,则无效
if any (" {0} ".format a in sentence for a in listword):

答案 3 :(得分:0)

>>> sentence="photos"
>>> listword=["os","slow"]
>>> pat = r'|'.join(r'\b{0}\b'.format(re.escape(x)) for x in listword)
>>> bool(re.search(pat, sentence))
False
>>> listword=["os","slow", "photos"]
>>> pat = r'|'.join(r'\b{0}\b'.format(re.escape(x)) for x in listword)
>>> bool(re.search(pat, sentence))
True

答案 4 :(得分:0)

虽然我特别喜欢标记化器和正则表达式解决方案,但我确实认为它们对于这种情况有点过分,只需使用str.find() method就可以非常有效地解决这个问题。

listword = ['os', 'slow']
sentence = 'photos'
for word in listword:
    if sentence.find(word) != -1:
       print 'yes'

虽然这可能不是最优雅的解决方案,但对于那些刚开始摆弄语言的人来说,它仍然是(在我看来)最合适的解决方案。