在python中使用get total函数

时间:2014-02-16 14:45:38

标签: python

任何人都可以帮我完成此代码,我需要计算文件中包含的数字总数,并使用get_total函数将答案打印到屏幕上。我有其余的代码运行正常我只是不知道如何将数字加在一起并显示答案。我正在使用python 3.3.2

def main():

     filename = input("Welcome, please enter file name:\t")
     menu()
     choice= int(input("Enter menu choice:\t"))

    while choice != 5:
         #get file choice from user
         if choice == 1:
             #create file
             create(filename)
         elif choice == 2:
             #read file
             read(filename)
         elif choice == 3:
             #append file
             append(filename)
         elif choice == 4:
             #get total
             get_total(filename)

         choice = int(input("Enter menu choice:\t"))

     print("\nApplication Complete")

 def menu():
     #user chooses a number from menu
     print("Choose a number to continue:\t\n\
     Select 1 to create a file\n\
     Select 2 to read a file\n\
     Select 3 to append to a file\n\
     Select 4 to calculate the total of a file\n\
     Select 5 to exit programme")

 def create(filename):

     #create file name
     outfile = open(filename,"w")
     again = "y"

      while again == "y":

         try:
             #user inputs integer
             num = int(input("Input number:\t"))
             outfile.write(str(num)+"\n")
             #asks user whether they want to continue or not
             again = input("Enter y to continue:\t")

         #if an error occurs
         except ValueError:
                       print("An error occured,please enter an integer:\t")

         except:
                       print("An undetermined error occurred")
      #close file
      outfile.close()

 def read(filename):

     print("\nReading File")

     try:
         #read integers entered onto file
         infile = open(filename,"r")

         for line in infile:

             number = int(line)
             print(number)

     except IOError:
             print("An error occured trying to read")
             print("the file", filename)

     except:
             print("An undefined error occurred")

 def append(filename):

     print("\nAppending to file")

     #user enters integers again
     outfile = open(filename, "a")
     again = "y"

     while again == "y":

         try:
             num = int(input("Input number to append to file:\t"))
             outfile.write(str(num)+"\n")
             again = input ("Enter y to continue:\t")

         except ValueError:
                 print("an error occured please an integer")
         except:
                 print("an undefined error occured")


         outfile.close()

 def get_total(filename):

     print("\nGetting total numbers contained in file")

     try:
         #user inputs integer
         num = int(input("Input number:\t"))
         outfile.write(str(num)+"\n")
         #asks user whether they want to continue or not
         again = input("Enter y to continue:\t")

     except IOError:
             print("An error occured trying to read")
             print("the file", filename)

     except:
             print("An undefined error occurred")          

 #call main
 main()

感谢您的帮助

3 个答案:

答案 0 :(得分:1)

import re
def get_total(filename):

    print("\nGetting total numbers contained in file")
    num = int(input("Input number:\t"))
    f = open(fileName)
    found = 0
    for line in f:
        for matchNum in re.findall(r'[0-9]+',line):
        if matchNum == str(num):
            found = found + 1
    print("\nNo. of occurrences of num in file :: ",found       

希望这能解决您的问题。

答案 1 :(得分:1)

这段代码对您的要求很有帮助:

def get_total(filename):
 total_sum = 0 
 print("Calculating total of the numbers contained in file")
 f = open(filename)
 try:
     #read inputs integer
     for line in f:  
         #split the string on whitespace, return a list of numbers
         # (as strings)
         numbers_str = line.split()
         #convert numbers to int
         numbers_int = [int(x) for x in numbers_str]

         total_sum=sum(numbers_int)

 except IOError:
         print("An error occured trying to read")
         print("the file", filename)

 except:
         print("An undefined error occurred")
 # prints out the total after the loop
 print("The total {}".format(total_sum))

答案 2 :(得分:0)

您需要创建一个变量来保存您正在阅读的所有数字:

 def get_total(filename):
     total_sum = 0 # running total
     print("\nGetting total numbers contained in file")

     try:
         #user inputs integer
         num = int(input("Input number:\t"))
         outfile.write(str(num)+"\n")
         total_sum += num
         #asks user whether they want to continue or not
         again = input("Enter y to continue:\t")

     except IOError:
             print("An error occured trying to read")
             print("the file", filename)

     except:
             print("An undefined error occurred") 
     # prints out the total after the loop
     print("The total {}".format(total_sum))