1

我正在編寫一個程序,記錄每個字母輸入的次數,以幫助我進行頻率分析。我的程序能夠工作,但它總是以曲線的形式輸出我的答案的一部分。示例輸出:我怎樣才能讓我的數據沿着python 3顯示?

Length of message: 591 characters 
A 11 1% 
B 27 4% 
C 37 6% 
D 2 0% 
E 2 0% 
F 5 0% 
G 17 2% 
H 8 1% 
I 9 1% 
J 49 8% 
L 7 1% 
M 44 7% 
N 20 3% 
P 42 7% 
Q 6 1% 
R 36 6% 
S 1 0% 
U 6 1% 
V 22 3% 
W 13 2% 
X 56 9% 
Y 11 1% 

我使用下面的代碼:

text = input() 
symbols = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 
letters = collections.Counter(text.upper()) 
length = len(text) 
print('Length of message: {} characters'.format(length)) 
for letter, times in sorted(letters.items()): 
    if letter not in symbols: 
     continue 
    percent = str(int((times/length) * 100)) + '%' 
    print(letter, times, percent) 

我試圖得到它顯示的是這樣的:

A 11 1% 
B 27 3% 
C 37 6% 
D 2 0% 
E 2 0% 
F 5 0% 
G 17 2% 
H 8 1% 
I 9 1% 
J 49 8% 
L 7 1% 
M 44 7% 
N 20 3% 
P 42 7% 
Q 6 1% 
R 36 6% 
S 1 0% 
U 6 1% 
V 22 3% 
W 13 2% 
X 56 9% 
Y 11 1% 

預先感謝您!

回答

0

取決於您想要如何顯示它。其中一種方法是在打印語句中添加選項卡。

例如:

print(letter,"\t", times,"\t", percent) 
1

與許多的空間墊:

print(('{:<2}{:<3}{:<3}').format(letter, times, percent)) 
0

既然你標記的Python 3.6,使用新f-strings

import collections 

text = input() 
symbols = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 
letters = collections.Counter(text.upper()) 
length = len(text) 
print(f'Length of message: {length} characters') 
for letter, times in sorted(letters.items()): 
    if letter not in symbols: 
     continue 
    percent = times/length 
    print(f'{letter} {times:2} {percent:5.1%}') 

沒有需要手動計算百分比字符串。只需計算浮點值percent = times/length並在f字符串中使用正確的格式。

{percent:5.1%}表示:將「percent」變量插入寬度爲5的字段中,並在小數點後一位。 %是一個格式說明符,將數字乘以100並添加百分號。 {letter}插入時沒有特殊格式,{times:2}默認爲數字右對齊的2寬字段。

輸出輸入的 「abbbbbbbbbbccc」:

Length of message: 14 characters 
A 1 7.1% 
B 10 71.4% 
C 3 21.4% 

參見: