簡體   English   中英

打印沒有換行符的字典?

[英]Printing a dictionary without newlines?

我正在嘗試在打印輸出上正確設置格式,這比應該的要復雜。 我的目標是讓我的代碼讀入字典,將其轉為列表,對其進行排序,然后將其打印回一個文本文件,如下所示:

“字符串”“浮動”

“字符串”“浮動”

“字符串”“浮動”

何時打印

浮動

浮動

查看作為我的字典的原始數據,它看起來像:

{'blahblah\n': 0.3033367037411527, 'barfbarf\n': 0.9703779366700716, 

我懷疑\\ n newline命令與此有關。 但是我似乎無法減輕它。 我的代碼如下:

#Open the text file and read it back it
h = open('File1.txt', 'r')
my_dict = eval(h.read())

#Print out the dictionary
print "Now tidying up the data......"
z = my_dict

#Turn the dictionary into a list and print it
j = open('File2.txt', 'w')
z = z.items()
z.sort(key=lambda t:t[1])
z.reverse()
for user in z:
    print >> j, user[0], user[1]
j.close()

該代碼幾乎可以在我的程序的所有其他部分正常工作。 由於某種原因,它在這里遇到了問題。

\\n是換行符。 寫入文件時,它顯示為換行符。 您應該在打印之前將其刪除:

print >> j, user[0].strip(), user[1].strip()

甚至更好,請在轉到列表時執行:

z = [item.strip() for item in z.items()]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM