【发布时间】:2017-09-28 11:19:09
【问题描述】:
我似乎无法弄清楚如何获得变量的百分比。这是确切的任务:
用 Python 编写一个程序,每行存储一个单词列表 文本文件,打印并计算长单词的数量,即单词 超过 10 个字符并表示 long 的百分比 单词,给定文本文件中的单词总数。
这是我的代码:
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))
【问题讨论】:
-
统计字数。计算 long 个单词的数量(都在同一个循环中)。 最后,当你把所有的东西都数完后,计算百分比。
-
对于初学者来说,
sys.stdin并不理想。最好定义路径,或使用sys.argv[1],并使用with open() as...打开/读取。 -
int(longwordcount // wordcount) * 100是 0 乘以 100,或 1 乘以 100。您可能是指longwordcount * 100 // wordcount。你应该在最后计算它,而不是你去。 -
我个人不会在这里使用
//(见上面的cmets),但如果你真的想尝试这样的东西。percentage = (100 * longwordcount) // wordcount -
啊,对,我可以用它!感谢您的帮助!
标签: python python-3.x