在Python中对照字典检查变量

2024-05-16 01:01:10 发布

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

好吧,我已经看过了,但是自从‘dictionary’这个词在Python中已经有了含义,所以我很挣扎。我指的是牛津(或其他)英语词典。在

我有一组单词。我想对它们进行循环检查,看看它们是否都在英语词典中。如果是,我想增加一个变量1。在

除了“让Python阅读字典”之外,这一切都很简单,我不太确定。我找到了一本可以用的.txt字典,但是里面的单词都有定义,所以不可能挑出真正的单词。在

有什么办法让我做到这一点吗?在


Tags: txtdictionary字典定义单词英语词典含义办法
2条回答

I have an array (list) of words. I want to loop though them and check if each one is in the English dictionary. If it is I want to increase a variable by 1.

如果我没听错,你可以这样做:

wordlist = ["foo", "bar", .....]
dictionary = …
words_in_dictionary = len([word for word in wordlist if word in dictionary])

This is all very simple apart from the 'getting Python to read a dictionary' which I'm not sure about. I have found a .txt dictionary which I could use but the words are in there with definitions making it impossible to pick out the actual words.

{cd2}你可以从unix中获得更好的单词。如果你把那本字典的一部分贴出来,我可以帮你。在

一旦你选择了一个合适的文件来创建你的单词表,你就可以使用^{}来跟踪你的列表中的单词是否出现在英语词典中。在

from collections import defaultdict

words = ['foo', 'bar', 'baz']
wordlist = open('linuxwords.txt').read().splitlines()
d = defaultdict(bool)
for word in words:
    d[word] = word in wordlist

for word in d:
    print "Does the word '{0}' appear in the English dictionary: {1}".format(word, "yes" if d[word] else "no")

结果:

^{pr2}$

相关问题 更多 >