3

我想编写一个函数来检查一个字母是否是一个单词的一部分,例如

"u" part of word in "i c u" = false
"u" part of word in "umbrella" = true
4

3 回答 3

6
>>> text = "i c u"
>>> letter = "u"
>>> any(letter in word and len(word) > 1 for word in text.split())
False
>>> text = "umbrella"
>>> any(letter in word and len(word) > 1 for word in text.split())
True

您可能会更改letter in wordletter.lower() in word.lower()取决于您是否区分大小写或nt。

于 2013-04-15T06:55:15.753 回答
0
>>> word = 'i c u'
>>> letter = 'u'
>>> letter in word.split(' ')
True
>>> word = 'umbrella'
>>> letter in word.split(' ')
False
于 2013-04-15T10:18:51.343 回答
0

假设您的意思是“在一个单词中”是“在任一侧至少有一个字符是“单词字符””,这将起作用:

import re
def letter_in_a_word(letter, words):
    return bool(re.search(ur'\w{0}|{0}\w'.format(letter), words))

letter_in_a_word('u', 'i c u') # False
letter_in_a_word('u', 'umbrella') # True
letter_in_a_word('u', 'jump') # True
于 2013-04-15T07:02:28.440 回答