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

3956 views python
1

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.

ratings=[] 
reviews=[]
def line_count(fname):
    with open("PlayStation-4-Console_reviews.txt") as text_file:
        for i, line in enumerate(text_file):
            pass
    return i+1
print(line_count("PlayStation-4-Console_reviews.txt"))

answered question

Could you add an example input and output?

2 Answers

4

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

if 'review' in line:
    reviews.append(line)
elif 'ratings' in line:
    ratings.append(line)

posted this
6

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 f.read().splitlines():
            if 'review' in line: reviews.append(line)
            elif 'rating' in line: reviews.append(line)


assert len(ratings) == len(reviews)

posted this

Have an answer?

JD

Please login first before posting an answer.