Python: trouble editing string in a text file -


so driving me crazy. need take text file containing (all in 1 line)

mmfff m fm fmm fff mmmmmm mfmfmf mmmfff mm fmmmf

and manipulate in program. needs open , read file, edit out spaces, , change letters caps. needs print edited file, count m's , f's , output them percent of whole.

# program determine male female ratio  import math  main = raw_input("enter name of 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." 

i have tried many ways, can't remember them now! issues it's not editing txt file properly, have letters @ end of string somehow. , refuses round math @ end i'm ending 58 , 41 when should 59. , yes did try round function, didn't help.

you have number of issues here:

  1. you're doing integer division, converting floats. fix try: mletter =((mletter*100)/39.0) instead.
  2. by using r+ mode overwrite file you're not erasing old content first. means when first run application remove spaces , overwrite beginning new contents , leave last few letters unchanged. try mode w instead.
  3. no need setting stuff 0 this: fletter = 0 overwrite in next line anyway.
  4. you're not using math module, no need import it.

(the result 58.97435897435898 way, not 59)


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -