如何在 python 类别中格式化我的数据

How format my data in category in python

一个python程序读取rainfall.txt文件然后写出一个新文件 称为 rainfallfmt.txt 。数据应按年总降雨量场分组为 以下类别:[60-70]、[71-80]、[81-90]、[91-]。在每个类别下,新的 文件应格式化每一行,使城市在 25 个字符宽的字段中右对齐,降雨数据应打印在 5 个字符宽的字段中,小数点右边有 1 位数字。 这是我目前所拥有的; 问题是我不知道如何分类? 你能帮助我并告诉我如何解决这个问题吗?

============================================= ===

 # read the rainfall.txt then write out a new file called rainfall.txt
    # the data should be grouped on the total annual rainfall field into the 
    # categories: [60-70], [71-80], [81,90], [91-]

        import os.path

        def main():
            endofprogram = False
            try:
                InputFileName = input('Enter name of input file: ')
                infile = open(InputFileName,'r')
                OutputFileName = input('Enter name of output file: ')
                # determine wether name exists
                while True:
                    if os.path.isfile(OutputFileName):
                        OutputFileName = input('File Exists. Enter name again: ')
                    else:
                        outfile = open(OutputFileName,'w')
                        break
            except IOError:
                print("Error opening file - End of program")
                endofprogram = True

                #If there is not exception, start reading the input file
                #Write the same data in formated form in new file.
                if endofprogram == False:
                    data = []
                    for line in infile:
                    .
                    .# I dont know what to do in here!
                    .
                    outfile.write(data[0])
        main()

你可以使用split分隔字段中的行(它returns一个字符串列表),然后获取降雨量,将其转换为浮点数,并使用每个类别的列表来存储数据。

cat_60 = []
cat_71 = []
cat_81 = []
cat_91 = []
for line in infile:
    city, rain = line.split(' ')    # Spliting using blank as separator
    rain = float(rain)

    if 60 <= rain <= 70:            # This works in Python as expected but don't in most other languages
        cat_60.append((city, rain)) # Storing a tuple at the end of the list
    elif 71 <= rain <= 80:
        cat_71.append((city, rain))
    # etc...

之后,您可以迭代类别并使用 str.format() 或使用 % 运算符格式化输出。

还有一些其他的事情可以让你的代码更像 Pythonic,例如变量名应该是 snakecase,titlecase 的名字应该保留给 类,大写的给常量,而不是使用标志变量您可以使用 and exit() 来结束程序。

仅当文件作为脚本调用时,您才可以执行以下操作来调用 main()

if __name__ == '__main__':
    main()
# read the rainfall.txt then write out a new file called rainfall.txt
# the data should be grouped on the total annual rainfall field into the 
# categories: [60-70], [71-80], [81,90], [91-]
import os.path

def main():

    endofprogram = False
    try:
        InputFileName = input('Enter name of input file: ')
        infile = open(InputFileName,'r')
        OutputFileName = input('Enter name of output file: ')
        # determine wether name exists
        while True:
            if os.path.isfile(OutputFileName):
                OutputFileName = input('File Exists. Enter name again: ')
            else:
                outfile = open(OutputFileName,'w')
                break
    except IOError:
        print("Error opening file - End of program")
        endofprogram = True

        #If there is not exception, start reading the input file
        #Write the same data in formated form in new file.
    if endofprogram == False:
        cat_60 = []
        cat_71 = []
        cat_81 = []
        cat_91 = []
        for line in infile:
            city, rain = line.split(' ')
            rain = float(rain)

            if 60 <= rain < 70:            
                cat_60.append((city, rain)) # Storing a tuple in the list
            elif 70 <= rain < 80:
                cat_71.append((city, rain))  
            elif 80 <= rain < 90:
                cat_81.append((city, rain))
            elif 90 <= rain :
                cat_91.append((city, rain))

        outfile.write("[60-70]"+'\n')
        for i in range(len(cat_60)):
            city = cat_60[i][0]
            rain = cat_60[i][1]
            outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')

        outfile.write("[70-80]"+'\n')
        for i in range(len(cat_71)):
            city = cat_71[i][0]
            rain = cat_71[i][1]                
            outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')

        outfile.write("[80-90]"+'\n')
        for i in range(len(cat_81)):
            city = cat_81[i][0]
            rain = cat_81[i][1]
            outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')

        outfile.write("[91-]"+'\n')
        for i in range(len(cat_91)):
            city = cat_91[i][0]
            rain = cat_91[i][1]
            outfile.write('%+25s'%(city)+'%5.1f'%(rain)+'\n')
main()