[英]How do you count two separate lines in a text file and assert that they are equal to one another?
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.给定一个包含一堆 playstation 4 评论的文本文件,我的任务是提取包含“评级:”和“评论:”的行,将它们保存到自己的列表中。 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"))
The expected outcome is预期的结果是
38096 38096
You can use the in keyword to check if one string is a substring of the other:您可以使用 in 关键字来检查一个字符串是否是另一个字符串的子字符串:
if 'review' in line:
reviews.append(line)
elif 'ratings' in line:
ratings.append(line)
Based Cory's answer you could do something like this:根据 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.