2017-10-07 38 views
0

我想打印出我有的結果列表,但我希望他們對齊。目前,他們看起來像:麻煩打印出來的東西,使他們對齊

 table   
word:   frequency: 
i     9 
my     2 
to     2 
test     2 
it     2 
hate     1 
stupid     1 
accounting     1 
class     1 
because     1 
its     1 
from     1 
six     1 
seven     1 
pm     1 
how     1 
is     1 
this     1 
helping     1 
becuase     1 
im     1 
going     1 
do     1 
a     1 
little     1 
on     1 
freind     1 
ii     1 

我想要的頻率相互以便它們不會在這個奇怪的曲折形式去對齊。我嘗試着在格式中加入東西,但沒有奏效。這是我的代碼看起來像:

import string 
from collections import OrderedDict 


f=open('mariah.txt','r') 
a=f.read() # read the text file like it would normal look ie no \n or anything 
# print(a) 
c=a.lower() # convert everything in the textfile to lowercase 
# print(c) 
y=c.translate(str.maketrans('','',string.punctuation)) # get rid of any punctuation 
# print(y) 
words_in_novel=y.split() # splitting every word apart. the default for split is on white-space characters. Why when i split like " " for the spacing is it then giving me \n? 

#print(words_in_novel) 

count={} 

for word in words_in_novel: 
    #print(word) 
    if word in count: # if the word from the word_in_novel is already in count then add a one to that counter 
     count[word]+=1 
    else: 
     count[word]=1 # if the word is the first time in count set it to 1 

print(count) 
print("\n\n\n\n\n\n\n") 
# this orderes the dictionary where its sorts them by the second term wehre t[1] refers to the term after the colon 
# reverse so we are sorting from greatest to least values 
g=(sorted(count.items(), key=lambda t: t[1], reverse=True)) 
# g=OrderedDict(sorted(count.items(), key=lambda t: t[1])) 
print(g) 
print("\n\n\n\n\n\n\n") 
print("{:^20}".format("table")) 
print("{}{:>20}".format("word:","frequency:")) 
for i in g: 
    # z=g[i] 
    # print(i) 
    # a=len(i[0]) 
    # print(a) 
    # c=50+a 
    # print(c) 
    print("{}{:>20}".format(i[0],i[1])) 

有誰知道如何使他們在一條直線?

+0

您所需要的單詞列有一個固定的寬度 –

回答

2

您需要調整第一列的寬度/寬度,而不是第二列。
正確方法:

... 
print("{:<20}{}".format("word:","frequency:")) 
for i in g: 
    print("{:<20}{}".format(i[0],i[1])) 

輸出會爲看:

word:    frequency: 
i     9 
my     2 
... 
accounting   2 
class    1 
because    1 
... 
+0

哇謝謝!爲什麼當你在第一個元素上做到這一點時會起作用? – Brit

+0

@Brit,不客氣。指定符'{:<20}'將第一列寬保留/擴展爲20個字符,並且左邊距爲 – RomanPerekhrest

+0

它是從行的開始位置延伸而不是當單詞結束時? – Brit

0

好吧,你的代碼的一部分:

for i in g: 
    r = " "*25 
    #print("{}{:>20}".format(i[0],i[1])) 
    r[:len(i[0])] = i[0] 
    r = r[:22]+str(i[1]) 
    print(r) 

它應該工作

0

如果你甚至會發現頻率大於一個數字就可以嘗試一些東西像這樣:

max_len = max(len(i[0]) for i in g) 
format_str = "{{:<{}}}{{:>{}}}".format(max_len, 20 - max_len) 
for i in g: 
    print(format_str.format(i[0], i[1])) 
0

對齊的話太

print("{:<10}{:>10}".format(i[0],i[1]))