所以我正在做一个项目,我从文件中找到单词,然后检查它是否在字典中。我不知道我是否遵循正确的语法,因为它打印出在字典中找不到“不起作用”的else语句。 它与中间的空格有什么关系吗?
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"
答案 0 :(得分:1)
要处理短语,您无法在格式word def
的字典文件中按空格分割一行,因为word
可能由多个带空格的单词组成在两者之间。你需要有一个不会出现在word
或def
中的字符来分隔它们,例如标签\t
或管道|
,然后像你的字典一样构建你的字典这样:
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]