单词字典问题

时间:2013-10-10 20:32:02

标签: python

我有一个起始文件,每行都有逗号分隔的值,如下所示:

hello,welcome
hi, howareyou
hola,comoestas

我想把这些单词放入字典中,这样它们就是键/值对。然后我试图要求一个键并返回相应的值。我相信我很亲密所以任何帮助将不胜感激。我也是初学者,所以简单的代码是最好的。

def CreateDictionary():


     WordDictionary = open('file.csv', 'r')
     for line in WordDictionary:
         mylist = line.split(',')
         return(mylist)


def main():

     cd = CreateDictionary()
     text=input('input text:')
     for x in cd.values():
        if x == text:
            word=cd[x]
            print(word)

main()

2 个答案:

答案 0 :(得分:1)

def makeDict(infilepath):
  answer = {}
  with open(infilepath) as infile:
    for line in infile:
      key,val = line.strip().split(',')
      answer[key] = val
    return answer

def main(infilepath):
  cd = makeDict(infilepath)
  key = input('input text: ')
  if key in cd:
    print(cd[key])
  else:
    print("'%s' is not a known word" %key)

答案 1 :(得分:0)

在这里,您可以编辑解决方案以创建字典。

def CreateDictionary():
    ret_dict = {}
    with open('file.csv', 'r') as WordDictionary:
        for line in WordDictionary:
            parts = line.split(',')
            ret_dict[parts[0]] = parts[1]
    return ret_dict


def main():
    cd = CreateDictionary()
    text = raw_input('input text:')
    word = cd[text]
    print word

main()

您的方法的一个主要问题是您在for循环中有return。该函数将在第一次循环迭代后返回,并且不会继续超出文件的第一行。