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% 

参见: