如何计算一个文本文件中的两行,并断言它们彼此相等?

时间:2018-11-04 17:45:15

标签: python jupyter-notebook

给出一个包含一堆Playstation 4评论的文本文件,我的任务是将它们保存到自己的列表中,以提取出包含“ rating:”和“ review:”的行。我需要能够使用

 assert len(ratings) == len(reviews)

命令以查找是否正确完成。结果应该就是两个人的长度。我可以算出整个文本文件的行数,但是完全无法理解如何按要求将其剪切。我是编程本身的业余爱好者。到目前为止,这就是我所拥有的。

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"))

预期结果是
38096

2 个答案:

答案 0 :(得分:1)

您可以使用in关键字来检查一个字符串是否是另一个字符串的子字符串:

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

答案 1 :(得分:0)

基于Cory的答案,您可以执行以下操作:

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)