2016-11-23 90 views
0

我试图将文件的内容存储到字典中,并且我认为我正确地做了它,但它并没有打印出所有的内容,只是第一行。我不知道我在做什么错,任何人都可以帮助我吗?从文件创建字典? Python

我使用的文件(mood.txt):

happy, Jennifer Clause 
sad, Jonathan Bower 
mad, Penny 
excited, Logan 
awkward, Mason Tyme 

我的代码:

def bringFile(): 

    moodFile = open("mood.txt") 
    moodread = moodFile.readlines() 
    moodFile.close() 
    return moodread 


def makemyDict(theFile): 
    for i in theFile: 
     (mood, name) = lines.split(",") 

     moodDict = {mood : name} 

     #print the dictionary 

     for m in moodDict: 
      return(m, name) 


def main(): 

    moodFile = bringFile() 

    mDict = makemyDict(moodFile) 

    print(mDict) 

我想检查字典是实际工作,这就是我为什么印刷它现在出来。每次我试着打印输出:

('happy', ' Jennifer Clause\n') 

我想都情绪/名字里面,所以我可以在以后使用它们分离出来的元素,但它只是似乎是打印出一对。我觉得我所有的步骤都是对的,所以我不知道该怎么做!

谢谢!

+2

你知道'return'声明做什么? – TigerhawkT3

+0

看起来你不清楚任务与突变之间的关系。 – TigerhawkT3

回答

0
def bringFile(): 
    moodFile = open("mood.txt",'r') 
    moodread = moodFile.readlines() 
    moodFile.close() 
    return moodread 

def makemyDict(theFile): 
    moodDict = {} 
    for lines in theFile: 
     mood, name = lines.split(",") 

     moodDict[mood] = name 

    return (moodDict) 
     #print the dictionary 

     # for m in moodDict: 
     #  return(m, name) 
     # print(lines) 

def main(): 

    moodFile = bringFile() 
    Dict = makemyDict(moodFile) 
    print(Dict) 

main() 
+0

谢谢你的回答! – naraemee

0

您正在重置每个循环的整个词典, 使用moodDict[mood] = name来设置一个键值对。

你也在回路内部,这将完全短路功能。您应该将for m in moodDict循环移到外部循环的外部,并使用print而不是return,或者在功能的末尾使用return moodDict,而不是在函数外部打印出来。

另一个需要注意的地方是,您可能需要拨打mood.strip()name.strip()来删除每个空格。

+0

感谢您解释它!我想我现在明白了! – naraemee

0

您正在返回for循环,所以基本上它只是进入for循环一次并返回。此外,您正在创建新的字典,在每次迭代中都写入moodDict。

def makemyDict(theFile): 
    moodDict = {} # create the dictionary 
    for i in theFile: 
     (mood, name) = lines.split(",") 
     moodDict['mood'] = name.strip() # strip off leading and trailing space 
    return moodDict 

顺便说一句,整个代码可以简化为以下

def makemyDict(theFile): 
    moodDict = {} # create the dictionary 
    with open(theFile) as f: 
     for line in f: 
      (mood, name) = lines.split(",") 
      moodDict['mood'] = name.strip() # strip off leading and trailing space 
    return moodDict 

d = makemyDict('mood.txt') 
print(d) 
+0

非常感谢你! – naraemee

+0

最好的感谢是upvote和/或接受你发现最有用的答案:)它也帮助其他人,当他们面临类似的问题 – Skycc

0
def line_gen(filename): 
    with open(filename) as f: 
     _ = (i.replace('\n', '').split(', ') for i in f) 
     yield from _ 

m_dict = dict([*line_gen('mode.txt')]) 
print(m_dict) 

出来:

{'awkward': 'Mason Tyme', 'excited': 'Logan', 'sad': 'Jonathan Bower', 'mad': 'Penny', 'happy': 'Jennifer Clause'} 
+0

谢谢你的回答! – naraemee