Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何在python中格式化类别中的数据_Python 3.x - Fatal编程技术网

Python 3.x 如何在python中格式化类别中的数据

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

一个python程序,读取rainum.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
在字段中分隔行(它返回字符串列表),然后获取雨量,将其转换为float,并使用每个类别的列表来存储数据

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...
#读取raining.txt,然后写出一个名为raining.txt的新文件
#数据应根据年总降雨量场分组到
#类别:[60-70],[71-80],[81,90],[91-]
导入操作系统路径
def main():
endofprogram=False
尝试:
InputFileName=input('输入输入文件的名称:')
infile=open(InputFileName,'r')
OutputFileName=input('输入输出文件的名称:')
#确定名称是否存在
尽管如此:
如果os.path.isfile(OutputFileName):
OutputFileName=input('文件存在。请再次输入名称:')
其他:
outfile=open(OutputFileName,'w')
打破
除IOError外:
打印(“打开文件时出错-程序结束”)
endofprogram=True
#如果没有异常,则开始读取输入文件
#在新文件中以格式化的形式写入相同的数据。
如果endofprogram==False:
cat_60=[]
cat_71=[]
cat_81=[]
cat_91=[]
对于填充中的线:
城市,雨=line.split(“”)
雨=漂浮(雨)

如果情况是这样的话。到目前为止你试过什么?检查。谢谢,你能帮我解决这个问题吗。我是python的新手。输入文件的格式如何?是txt,这里是它的数据:阿克伦65.5574阿尔比亚95.631阿尔冈那77.9526阿利森85.4456阿尔顿69.6722阿梅斯瓦86.5378阿梅塞86.233阿纳莫萨89.7382安肯尼84.7852大西洋88.3158奥杜邦84.8614比康斯菲尔德89.5858贝德福德92.329贝勒普莱恩90.9574贝勒维87.249布洛克顿92.1512布隆菲尔德96.5708布恩92.202布莱顿85.3186布里特80.1116七叶树85.4964 BurlingtonKBUR 96.3676 Burlington 93.8276 Carroll 84.6582 Cascade 85.0392此外,每个数据都在单独的一行中。谢谢,:)但现在的问题是,在我的输出文件中没有数据!?:(你不应该把它作为一个答案。无论如何,如果你的
缩进过多,它就在
中,除了
子句。同样在
输出文件的调用中。写
你有语法错误,要保存列表的内容,你必须遍历它们,并使用
str.format
%将其内容格式化为字符串。
接线员。我不知道你这是什么意思?!谢谢,我真的很感谢你抽出时间,我只是想弄明白,问题出在哪里。我会编辑我的答案并与大家分享。再次感谢。:)无论是
format()
还是
%
的格式字符串都可以进行多次转换,通常您会编写类似于
'%+25s%5.1f\n%%(city,rain)
或使用
format()
'{:>25s}{:5.1f}\n.格式(city,rain)
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()