看板 Python 關於我們 聯絡資訊
先讀入兩個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
LiloHuang:請用 writing.writelines(str(list2dict(book1+book2))) 04/25 14:15
harohepowegr:謝謝QQ 04/25 15:12