在让我的输出以某种方式看起来有问题

时间:2010-10-24 22:06:22

标签: python

感谢您查看我的问题,并提前感谢您提供的任何帮助。 我正在编写一个程序,从txt文件中读取行,然后以某种方式打印输出。在这里他们都是

这是我正在阅读的txt文件

JOE FRITZ           AMERICAN GOVERNMENT           B
JOE FRITZ           CALCULUS I                    A
JOE FRITZ           COMPUTER PROGRAMMING          B
JOE FRITZ           ENGLISH COMPOSITION           A
LANE SMITH          FUND. OF DATA PROCESSING      B
LANE SMITH          INTERMEDIATE SWIMMING         A
LANE SMITH          INTRO. TO BUSINESS            C
JOHN SPITZ          CHOIR                         C
JOHN SPITZ          COLLEGE STATISTICS            B
JOHN SPITZ          ENGLISH LITERATURE            D
JOHN SPITZ          INTRO. TO BUSINESS            B

我试图让我的输出看起来像这样:

                       GRADE REPORT

NAME                COURSE                            GRADE
-----------------------------------------------------------
JOE FRITZ           AMERICAN GOVERNMENT                 B
                    CALCULUS I                          A
                    COMPUTER PROGRAMMING                B
                    ENGLISH COMPOSITION                 A
                    Total courses taken = 4

LANE SMITH          FUND. OF DATA PROCESSING            B
                    INTERMEDIATE SWIMMING               A
                    INTRO. TO BUSINESS                  C
                    Total courses taken = 3

JOHN SPITZ          CHOIR                               C
                    COLLEGE STATISTICS                  B
                    ENGLISH LITERATURE                  D
                    INTRO. TO BUSINESS                  B
                    Total courses taken = 4

Total courses taken by all students = 11

Run complete.  Press the Enter key to exit.

修改

感谢您的帮助,我完成了这个计划。

我知道这可能很难看,但ATM我很高兴能让输出正确。

以下是显示正确输出的来源:

#-----------------------------------------------------------------------
# VARIABLE DEFINITIONS

name = ""
previousName = ""
course = ""
grade = ""
grandTotal = 0
courseCount = 0
eof = False

#-----------------------------------------------------------------------
# CONSTANT DEFINITIONS

#-----------------------------------------------------------------------
# FUNCTION DEFINITIONS

def startUp():
    global gradeFile, grandTotal,courseCount, previousName, name
    grandTotal = 0
    courseCount = 0
    gradeFile = open("grades.txt","r")
    print
    print ("grade report\n").center(60).upper()
    print "name".upper(),"course".rjust(21).upper(),"grade".rjust(33).upper()
    print "-" * 60
    readRecord()


def readRecord():
    global name, course, grade, eof, courseCount

    studentRecord = gradeFile.readline()
    if studentRecord == "":
        eof = True
    else:
        name = studentRecord[0:20]
        course = studentRecord[20:50]
        grade = studentRecord[50:51]
        eof = False

def processRecords():
    global courseCount, previousName, name, grandTotal
    while not eof:
        if name != previousName:
            if name == "JOE FRITZ           ":
                courseCount = 0
                print name + course + "       " + grade
                previousName = name
                courseCount += 1
            else:
                print "\t\t    Total courses taken =",courseCount 
                print
                courseCount = 0
                print name + course + "       " + grade
                previousName = name
                courseCount += 1
        else:
            print (" " * 20) + course + "       " + grade
            courseCount += 1
        grandTotal +=1
        readRecord()
    print "\t\t    Total courses taken =",courseCount


def closeUp():
    gradeFile.close()
    print "\nTotal courses taken by all students =",grandTotal

#-----------------------------------------------------------------------
# PROGRAM'S MAIN LOGIC

startUp()
processRecords()
closeUp()

raw_input("\nRun complete. Press the Enter key to exit.")

感谢大家的帮助。我真的很感激。对不起,如果我在此过程中让任何人感到沮丧。祝你有个好的一天。和平

2 个答案:

答案 0 :(得分:3)

我只是在函数readRecord()中找出代码中的一个错误,你只是在阅读文件的第一行;你应该遍历所有行或使readRecord()成为一个生成器。

  def readRecord():
     global name, course, grade, eof

     studentRecord = gradeFile.readline()  # <----- HERE

     if studentRecord == "":
        eof = True
     else:
        name = studentRecord[0:20]
        course = studentRecord[20:50]
        grade = studentRecord[50:51]
        eof = False

但是尽管如此,为了真诚,我不喜欢你的代码,如果我是你,我会做的就是:

1)以任何方式从文件中获取数据(csv,regex ...);我想我们已经在here

中得到了答案

2)将数据放入字典或其他内容(这样你就可以操纵它们了。)

3)使用itertools.groupby()按学生分组并计算您想要的总和。

4)使用字符串Template(),因为格式可能会改变,并且不像你那样硬编码输出格式。

并且请在写入之后逐个测试您的功能,因为如果不这样做,将很难弄清楚代码的哪个部分不起作用。

修改

我不会问你为什么要这样做,因为如果你想再把它们放在一个文件中,你会遇到和以前一样的问题,如果你想再次检索它们,如果你的目标只是为了做一个漂亮的输出我会问你是否值得?

最后一个建议使用熟知的格式,如csv,xml ......

祝你好运:)。

答案 1 :(得分:0)

这可能不是您的愚蠢教练希望您这样做的20世纪60年代COBOLlocks方式,但一般的想法是:

(1)itertools.groupby可以为您节省所有先前/当前检测名称更改的malarky

(2)你应该预先将你的数据记录提取成合理的格式 - 剥离尾随空格(总是一个好主意)摆脱不属于数据的杂散换行

(3)像你一样使用的全局变量是完全的痘(用任何语言)。

import itertools

guff = """\
JOE FRITZ           AMERICAN GOVERNMENT           B
JOE FRITZ           CALCULUS I                    A
JOE FRITZ           COMPUTER PROGRAMMING          B
JOE FRITZ           ENGLISH COMPOSITION           A
LANE SMITH          FUND. OF DATA PROCESSING      B
LANE SMITH          INTERMEDIATE SWIMMING         A
LANE SMITH          INTRO. TO BUSINESS            C
JOHN SPITZ          CHOIR                         C
JOHN SPITZ          COLLEGE STATISTICS            B
JOHN SPITZ          ENGLISH LITERATURE            D
JOHN SPITZ          INTRO. TO BUSINESS            B
"""

data_source = guff.splitlines(True) # simulate file

columns = (slice(0, 20), slice(20, 50), slice(50, 51))

def data_reader(raw_record_iterator):
    for line in raw_record_iterator:
        yield [line[sl].rstrip() for sl in columns]

def process_file():

    # f = open('my_file.text', 'r')
    # or use a 'with' statement
    # data_source = f

    for key, grouper in itertools.groupby(
            data_reader(data_source), lambda element: element[0]):
        print "=== start student %s ===" % key
        for cooked_record in grouper:
            print cooked_record
        print "=== end student %s ===" % key
    print "=== Grand totals here ==="
    # f.close()

if __name__ == "__main__":
    process_file()

实际输出:

=== start student JOE FRITZ ===
['JOE FRITZ', 'AMERICAN GOVERNMENT', 'B']
['JOE FRITZ', 'CALCULUS I', 'A']
['JOE FRITZ', 'COMPUTER PROGRAMMING', 'B']
['JOE FRITZ', 'ENGLISH COMPOSITION', 'A']
=== end student JOE FRITZ ===
=== start student LANE SMITH ===
['LANE SMITH', 'FUND. OF DATA PROCESSING', 'B']
['LANE SMITH', 'INTERMEDIATE SWIMMING', 'A']
['LANE SMITH', 'INTRO. TO BUSINESS', 'C']
=== end student LANE SMITH ===
=== start student JOHN SPITZ ===
['JOHN SPITZ', 'CHOIR', 'C']
['JOHN SPITZ', 'COLLEGE STATISTICS', 'B']
['JOHN SPITZ', 'ENGLISH LITERATURE', 'D']
['JOHN SPITZ', 'INTRO. TO BUSINESS', 'B']
=== end student JOHN SPITZ ===
=== Grand totals here ===