-1

所以我正在做一个项目,我从文件中查找单词,然后检查它是否在字典中。我不知道我是否遵循正确的语法,因为它会打印出在字典中找不到“不起作用”的 else 语句。和中间的空格有关系吗?

用多个单词测试术语 - 不起作用:-3

if 'does not work' in dictionary:
    expected_value3 = str(-3)
    actual_value3 = dictionary['does not work']
    if actual_value3 == expected_value3:
        print "---------------------------------"
        print "words with spaces passes| word: does not work"
    else:
        print "---------------------------------"
        print "words with spaces FALSE| word: does not work"
else:
    print "---------------------------------"
    print "does not work not in dictionary"
4

1 回答 1

1

要处理短语,您不能在格式的字典文件word def中用空格分隔一行,因为word它可能由几个单词组成,中间有空格。您需要有一个不会出现worddef分隔它们的字符,例如 tab\t或 pipe |,然后像这样构建您的字典:

d = {}
with open('dict.txt') as df:
    for line in df:
        word,definition = line.split('\t')
        d[word] = definition

否则你最终会得到

sentiments = ['does','not','work','the','operation',...]

在你的循环中,你最终设置

dictionary['does'] = 'not'

用代码

for line in scores_file:
    sentiments = line.split()
    dictionary[sentiments[0]] = sentiments[1]
于 2013-08-24T03:52:36.607 回答