用python解析单词表

2024-06-03 02:49:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含大约58k个英语单词的wlist.txt文件,其中一小部分如下:

aardvark
aardwolf
aaron
aback
abacus
abaft
abalone
abandon
abandoned
abandonment
abandons
abase
abased
abasement

我想做的是让程序在列表中搜索,看看列表中是否包含一个单词,如果包含,则打印该单词。我的问题是,我编写的代码将不断返回不,这个词不在列表中,当我确定它是。我的代码看起来是这样的,有人注意到任何错误吗?

match = 'aardvark'
f = 'wlist.txt'
success = False
try:
    for word in open(f):
        if word == match:
            success = True
            break
except IOError:
    print f, "not found!"
if success:
    print "The word has been found with a value of", word
else:
    print "Word not found"

提前谢谢大家!!


Tags: 文件代码txt列表ifmatchnot单词