How do you count two separate lines in a text file and assert that they are equal to one another?

3956 views python

Given a text file that includes a bunch of playstation 4 reviews I'm tasked with extracting out the lines that include "rating:" and "review:" by saving them to their own lists. I need to be able to use the

 assert len(ratings) == len(reviews)

command to find out if it was done right. The outcome should just be what the length is for both of them. I can count the lines of the entire text file but am completely and utterly lost at how to cut it up like asked. I am an utter amateur at programming itself. This is what I have so far.

def line_count(fname):
    with open("PlayStation-4-Console_reviews.txt") as text_file:
        for i, line in enumerate(text_file):
    return i+1

answered question

Could you add an example input and output?

2 Answers


You can use the in keyword to check if one string is a substring of the other:

if 'review' in line:
elif 'ratings' in line:

posted this

Based Cory's answer you could do something like this:

ratings = []
reviews = []

def line_count(filename="PlayStation-4-Console_reviews.txt"):
    with open(filename) as f:
        for line in
            if 'review' in line: reviews.append(line)
            elif 'rating' in line: reviews.append(line)

assert len(ratings) == len(reviews)

posted this

Have an answer?


Please login first before posting an answer.