2016-11-23 91 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