[问题] 函式写入txt

楼主: harohepowegr (harohepowegr)   2014-04-25 13:41:05
先读入两个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
没有办法出现计算几次,然后字还全部连在一起@@
作者: LiloHuang (十年一刻)   2014-04-25 14:15:00
请用 writing.writelines(str(list2dict(book1+book2)))
楼主: harohepowegr (harohepowegr)   2014-04-25 15:12:00
谢谢QQ

Links booklink

Contact Us: admin [ a t ] ucptt.com