Search code examples
python-2.7file-writing

How to Select Recurring Text in a File


I'm Writing a code, where the user can input one option out of a multiple choice selection. Whatever answer they give, such as "a" or "b", gets written as either "Correct" or "Not Correct" into a separate text file, (StudentAnswers.txt). Obviously, the new text file will be filled with multiple lines of "Correct", and "Incorrect"

This part has already been achieved, but can someone please show me how to create a code which reads the text file "StudentAnswers", and if the total number of recurring "Correct" values is greater or equal to half, print "Passed", or if not print "Fail"

Hope you guys Understand. Thanks.


Solution

  • You can read the file lines and filter them either for "Correct" or for "Not Correct".

    lines = open(file).readlines()
    total = len(lines)
    totalOK = len(filter( lambda x: x == "Correct\n") lines)
    if totalOK >= total / 2:
        print "Passed"
    else:
        print "Failed"
    

    If you are not familiar with lambda and filter you can do it this way:

    def countOK ( lines ):
        cnt = 0
        for i in lines:
            if i == "Correct\n":
                cnt += 1
        return cnt
    ...
    lines = open( file ).readlines()
    total = len( lines )
    totalOK = countOK (lines)
    if totalOK >= total / 2:
        print "Passed"
    else:
        print "Failed"