我有一个代码可以创建文本文件中某些字长的百分比丰度列表,例如13%的时间出现1个字母的单词,我想知道的是,如果在50,000字的文本文件中有1个20个字母的单词,是否将20个字母单词的比例降低到0或1?Python中的百分比和舍入
这里是整个代码:
lines = open ('E:\Videos, TV etc\Python\Assessment\dracula.txt', 'r'). readlines()
stripped_list = [item.strip() for item in lines]
tally = [0] * 20
print tally #original tally
for i in stripped_list:
length_word = int(len(i))
tally[length_word-1] += 1 #adds 1 to the tally for the index of that word length, (length_word)-1 used as the tally for 1 letter words are in the 0 index
print tally
new_tally = [] #this tally will contain the occurences of each word length by percentage
for a in tally:
new_tally.append((100*a)/(sum(tally))) # multiplies by 100 and divides by all of the tallies to give a percentage
print new_tally
为了回答这个问题,我们需要看看你是如何计算您的百分比以及四舍五入是如何被做。 – Acorn
除非您发布代码,否则很难说清楚。 – Kevin
它完全取决于正在做什么取整。你正在使用'print'%.2f“%value'还是某种字符串格式? – chown