获取Python 3中变量的百分比

时间:2017-09-28 11:19:09

标签: python python-3.x

我似乎无法弄清楚如何获得变量的百分比。这是确切的任务:

  

用Python编写程序,每行存储一个单词列表   一个文本文件,打印并计算长词的数量,即单词   超过10个字符,表示长的百分比   给定文本文件中单词总量的单词。

这是我的代码:

wordcount = 0
longwordcount = 0

for line in sys.stdin:
    line = line.rstrip()
    charnum = len(line)
    wordcount = wordcount + 1
    percentage = int(longwordcount // wordcount) * 100
    if charnum > 10:
         longwordcount = longwordcount + 1
         print(line)



print("There are {0} words in the word list that have more than 10 characters.\nThis is {1}% of the total number of words in the text file." 
.format(longwordcount, percentage))

1 个答案:

答案 0 :(得分:0)

使用除法运算符代替换层运算符而不是int类型转换。如果需要,您可以使用格式语句来限制位数。

percentage = longwordcount / wordcount * 100