所以这让我发疯了。我需要一个包含(所有在一行)的文本文件
mmfff m fm fmm FFF mmmmmm mfmfmf mmmfff MM fmmmf
并在程序中操作它。它需要打开并读取文件,编辑空格,并将所有字母更改为大写字母。然后它需要打印编辑过的文件,计算m和f并将它们输出为整体的百分比。
# A program to determine male to female ratio
import math
main = raw_input("Enter the name of your file: ")
inputFile = open(main, 'r+')
gender =(inputFile.read().replace(" ", "").replace("f", "F").replace("m", "M"))
inputFile.close()
inputFile= open(main, 'r+')
inputFile.write(gender)
inputFile.close()
print gender
fletter = 0
mletter = 0
mletter = gender.count('M')
fletter = gender.count('F')
mletter =((mletter*100)/39)*1.0
fletter =((fletter*100)/39)*1.0
print "There are", mletter, " males and", fletter, " females."
我尝试了很多方法,现在我甚至都记不起来了!我的问题是它没有正确编辑txt文件,我在字符串的末尾有多余的字母。并且它最终拒绝围绕我的数学运算,所以当它应该是59时我最终会得到58和41.而且我确实尝试了圆函数,没有帮助。
答案 0 :(得分:0)
我在下面的代码中做了一些改进。内联注释解释了每个部分的作用以及它对您的初始尝试所做的改进。
main = raw_input("Enter the name of your file: ")
# make this a function since we use the equation more than once
def get_percent(part, whole):
return 100 * float(part)/float(whole)
# make sure we handle the file not existing
try:
with open(main, 'r+') as fd:
# replace
newstr = fd.read().replace(' ', '').upper()
# after reading the file the file pointer will be at the end, we need to seek
# back to the start of the file
fd.seek(0)
# remove the existing file contents
fd.truncate()
fd.write(newstr)
except IOError:
# provide a friendly error and exit instead of a stacktrace
raise SystemExit("Failed to open file %s" % main)
mletter = newstr.count('M')
fletter = newstr.count('F')
total = len(newstr)
# Using string formatting is often easier to read than string concatentation
print "There are %s%% males and %s%% females" %(
get_percent(mletter, total),
get_percent(fletter, total)
)