0

ここに助けが必要なコードがあります。

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

写真にosが存在するため、yesと出力されます。しかし、「単語」が単語の一部として存在するのではなく、文字列に存在する osがあるかどうかを知りたい.文を単語のリストに変換せずに方法はありますか. .文字列に os wordが含まれている場合にのみ、yes を出力する必要があります。

ありがとう

4

5 に答える 5

0

While I especially like the tokenizer and the regular expression solutions, I do believe they are kind of overkill for this kind of situation, which can be very effectively solved just by using the str.find() method.

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

Although this might not be the most elegant solution, it still is (in my opinion) the most suitable solution for people that just started out fiddling with the language.

于 2013-04-17T08:40:39.100 に答える
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
于 2013-04-17T08:29:01.257 に答える