【问题标题】:ASCII Text to ASCII Number converter with apperance frequency and asterisks in pythonASCII文本到ASCII数字转换器,在python中具有出现频率和星号
【发布时间】:2021-01-01 17:30:41
【问题描述】:

我是编程领域的新手,我需要您帮助解决我面临的问题。我正在创建一个 Python 程序,该程序将 ASCII 文本作为输入,将其字符转换为 ASCII 数值,然后删除偶数并最终将剩余的重复频率显示为百分比和星号(*)。一个星号表示为 1%(即 5% = 5 个星号)。

我在显示星号值时遇到问题。下面你可以看到我从 VS 代码中得到的结果。

f = open(r"c:\python\7_ASCII\Sample.txt", "r")
my_text = f.read()
ascii = []
for word in my_text:
    ascii_word = []
    for char in word:
        ascii_word.append(ord(char))
    ascii.append(ascii_word)
print('Λίστα Δύο Διαστάσεων:',ascii)

flatten_ascii = [val for sublist in ascii for val in sublist]
print('Λίστα Μίας Διάστασης:',flatten_ascii,)

def remove_even(flatten_ascii):
    odd_list = []
    for i in flatten_ascii:
        if i % 2 != 0:
            odd_list.append(i)
    return odd_list
print('Λίστα Μονών ASCII:',remove_even(flatten_ascii))

all_freq = {}
for i in (remove_even(flatten_ascii)):
    if i in all_freq:
        all_freq[i] += 1
    else:
        all_freq[i] = 1
print(str(all_freq))

count = Counter(remove_even(flatten_ascii)).items()

percentages = {x: int(float(y) / len(remove_even(flatten_ascii)) * 100) for x,y in count}

for name, pct in percentages.items():
        print('%s - %s%s' % (name, pct, '%'))

这是我得到的输出(我只给你百分比输出,以避免混淆)

{121: 1, 111: 3, 105: 4, 115: 2, 97: 6, 101: 9, 103: 6, 45: 2, 117: 2, 109: 2}
121 - 2%
111 - 8%
105 - 10%
115 - 5%
97 - 16%
101 - 24%
103 - 16%
45 - 5%
117 - 5%
109 - 5%

关于如何显示以下输出的任何想法?

121 - ** 2% 
111 - ******** 8%
105 - ********** 10%
115 - ***** 5%
97 - **************** 16%
101 - ************************ 24%
103 - **************** 16%
45 - ***** 5%
117 - ***** 5%
109 - ***** 5%

【问题讨论】:

    标签: python list ascii percentage


    【解决方案1】:

    自从

    5*'*' == *****
    

    为什么不这样使用:

    print('{} - {} {}%'.format(name,'*'*pct,pct))
    #or
    print('%s - %s %s%s' % (name,pct*'*',pct,'%'))
    

    【讨论】:

    • 非常感谢我的朋友,我已经尝试解决这个问题好几个小时了。对不起,这是我的第一个问题,我不能投票给你。顺便说一句,由于我是 Python 新手,5*'*' 是什么意思???有什么文档可以搜索吗?
    • 字符串乘法
    猜你喜欢
    • 2011-03-31
    • 2014-04-07
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 2018-08-28
    • 2014-09-23
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多