我试图找到一个单词是否在文件中,而不是如果它是部分单词的一部分。例如,如果word = 'tes'
and'test'在单词列表中,我希望它返回False。我找到了可以通过正则表达式进行操作的地方,但是由于我所学的内容还没有涵盖这一部分,所以我想看看如果没有它,我是否可以实现这一点。
这是我到目前为止所拥有的:
WORDLIST_FILENAME = "words.txt"
def isValidWord(word, hand, wordList):
letters = {}
for i in word:
letters[i] = letters.get(i, 0) + 1
if word.upper() in open(wordList).read():
for i in letters:
if i in hand:
if hand[i] >= letters[i]:
continue
else:
return False
else:
return False
return True
else:
return False
word = 'tes'
hand = {'t': 3, 'a': 1, 's': 1, 'i': 1, 'n': 1, 'g': 1}
print(isValidWord(word, hand, 'words.txt'))
即使'tes'实际上不在word.txt中,它也会返回True。我知道为什么,因为我正在检查该字符串是否在文件周期内,但是我不知道如何解决。
您可能想要检查in
关键字,因为它看起来像您想要的。
这是一个简单的例子:
>>> word = "some"
>>> sentence = "This is a sentence with some words."
>>> word in sentence
True
由于您不希望它与部分单词匹配,因此可以删除所有非字母字符,然后删除split
字符串:
>>> sentence = ''.join(char for char in sentence if char.isalpha() or char.isspace()).split()
>>> "words" in sentence
True
>>> "word" in sentence
False
老实说,我只是为此使用正则表达式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句