[問題] 函式寫入txt

看板Python作者 (harohepowegr)時間11年前 (2014/04/25 13:41), 編輯推噓1(101)
留言2則, 2人參與, 最新討論串1/2 (看更多)
先讀入兩個txt檔 b1 This is a book This is a pen This is a table This is a desk b2 This is a papaya This is a pineapple This is a banana This is a melon 以下為程式碼 #讀檔函式 def readbook(filename): readin = open(filename) count = [] for line in readin: letter = line.split() count = count + letter return count #計算出現次數 def list2dict(count): ldict = dict() for ch in count: ldict[ch]=ldict.get(ch,0)+1 return ldict book1 = readbook('b1.txt') book2 = readbook('b2.txt') text = list2dict(book1+book2) print('全部出現的單字和次數') print(list2dict(book1+book2)) #寫檔 ←這邊有奇妙的問題 writing = open('writeout.txt','w') writing.writelines("全部出現的單字和次數\n") writing.writelines(list2dict(book1+book2)) writing.close() ============================================================================== outprint出來的結果為: 全部出現的單字和次數 {'desk': 1, 'is': 8, 'This': 8, 'a': 8, 'banana': 1, 'papaya': 1, 'pineapple': 1, 'table': 1, 'melon': 1, 'pen': 1, 'book': 1} 但寫進txt後就變成: 全部的單字 deskisThisabananapapayapineappletablemelonpenbook 沒有辦法出現計算幾次,然後字還全部連在一起@@ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 163.14.36.25 ※ 文章網址: http://www.ptt.cc/bbs/Python/M.1398404468.A.14C.html

04/25 14:15, , 1F
請用 writing.writelines(str(list2dict(book1+book2)))
04/25 14:15, 1F

04/25 15:12, , 2F
謝謝QQ
04/25 15:12, 2F
文章代碼(AID): #1JMVLq5C (Python)
討論串 (同標題文章)
文章代碼(AID): #1JMVLq5C (Python)