【问题标题】:How can I get my data to be displayed along a line with python 3?如何让我的数据与 python 3 一起显示?
【发布时间】:2017-02-20 18:53:11
【问题描述】:

我正在编写一个程序来计算每个字母的输入次数,以帮助我进行频率分析。我的程序有效,但它总是沿曲线输出我的部分答案。示例输出:

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%

提前谢谢你!

【问题讨论】:

    标签: python python-3.x data-visualization frequency-analysis python-3.6


    【解决方案1】:

    用多个空格填充:

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

    【讨论】:

      【解决方案2】:

      取决于您希望如何显示它。其中一种方法是在您的打印语句中添加选项卡。

      例如:

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

      【讨论】:

        【解决方案3】:

        既然您标记了 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%} 表示:在此处插入“百分比”变量,宽度为 5,小数点后一位。 % 是一个格式说明符,它将数字乘以 100 并添加一个百分号。 {letter} 插入时没有特殊格式,{times:2} 生成一个 2 宽的字段,默认情况下数字右对齐。

        输入“abbbbbbbbbbccc”的输出:

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

        另见:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-09-23
          • 2018-04-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多