获取Python 3中变量的百分比
我似乎不知道如何得到一个变量的百分比。下面是确切的任务: 用Python编写一个程序,该程序包含存储在每行上的单词列表 在文本文件中,打印并计算长字数,即字数 具有10个以上字符并指示长字符百分比的 单词,给定文本文件中的单词总数 这是我的代码:获取Python 3中变量的百分比,python,python-3.x,Python,Python 3.x,我似乎不知道如何得到一个变量的百分比。下面是确切的任务: 用Python编写一个程序,该程序包含存储在每行上的单词列表 在文本文件中,打印并计算长字数,即字数 具有10个以上字符并指示长字符百分比的 单词,给定文本文件中的单词总数 这是我的代码: wordcount = 0 longwordcount = 0 for line in sys.stdin: line = line.rstrip() charnum = len(line) wordcount = wordc
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))
使用除法运算符而不是楼层除法运算符,而不是int类型转换。如果需要,可以使用format语句限制位数
百分比=longwordcount/wordcount*100计算字数。计算同一循环中所有长单词的数量。最后,当您计算完所有内容后,计算百分比。对于初学者来说,sys.stdin并不理想。最好定义路径,或者使用sys.argv[1],并使用open as打开/读取……intlongwordcount//wordcount*100是0乘以100,或者1乘以100。你可能是指longwordcount*100//wordcount。你应该在最后计算它,而不是在你走的时候。我个人不想在这里使用//看到上面的评论,但是如果你真的想尝试这样的东西。百分比=100*longwordcount//WordCountah好的,我可以用这个!谢谢你的帮助!