[英]Print number of lines found
New to programming here and was wondering if anyone could help me out: 这里的编程新手,想知道是否有人可以帮助我:
I'm trying to print or return the number of lines found in the below code using one line and I can't figure it out. 我正在尝试使用一行打印或返回以下代码中找到的行数,但我无法弄清楚。
query = raw_input("Enter string to search for: ")
for line in open("list2.csv"):
if query in line:
print line,
Use a list comprehension like this: 使用这样的列表理解:
with open("list2.csv") as f:
print(sum(query in line for line in f)) #gives number of lines found
There have been identical questions asked on here: 在这里有人问过相同的问题:
How to get line count cheaply in Python? 如何在Python中便宜地获得行数?
Here is the method that thread provides: 这是线程提供的方法:
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
Search is your friend :). 搜索是您的朋友:)。
I would suggest for clarity that you avoid using just a single line! 为了清楚起见,我建议您避免只使用一行! Here is something that should work:
这应该可行:
query = raw_input("Enter string to search for: ")
lines = []
for line in open("list2.csv"):
if query in line:
lines.append(line)
print line,
print "Number of lines:", len(lines)
If you really wanted a single line, you could do the following: 如果您确实想要一行,则可以执行以下操作:
query = raw_input("Enter string to search for: ")
print "Number of lines:", len([line for line in open("list2.csv") if query in line])
Not sure if this would be the best option, but it's the easiest. 不知道这是否是最好的选择,但这是最简单的。
Add a counter to your if
statement to increase by one for every time the if
statement executes. 计数器添加到您
if
语句由一个为每个时间的增加if
语句执行。
Try this: 尝试这个:
counter = 0
query = raw_input("Enter string to search for: ")
for line in open("list2.csv"):
if query in line:
print line
counter += 1
return counter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.