我是编程领域的新手,需要您帮助解决我面临的问题。我正在创建一个Python程序,它以ASCII文本作为输入,将其字符转换为ASCII数值,然后删除偶数&最后将剩余的重复频率显示为百分比和星号(*(。一个星号表示为1%(即5%=5个星号(。
我在显示星号值时遇到问题。下面你可以看到我从VS代码中得到的结果。
f = open(r"c:python7_ASCIISample.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%
由于
5*'*' == *****
为什么不这样使用:
print('{} - {} {}%'.format(name,'*'*pct,pct))
#or
print('%s - %s %s%s' % (name,pct*'*',pct,'%'))