[問題] 函式寫入txt
先讀入兩個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
04/25 14:15, 1F
→
04/25 15:12, , 2F
04/25 15:12, 2F
討論串 (同標題文章)
Python 近期熱門文章
PTT數位生活區 即時熱門文章