我有一個代碼可以創建文本文件中某些字長的百分比丰度列表,例如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