简体   繁体   English

如何打印过滤结果所在的行?

[英]How do you print a line that filtered results are on?

I'm trying to find a value from a txt that contains 2 words in a single line, the first word has to have a length longer than 10. I want my result to be printed with result and the line that my result is on.我试图从包含 2 个单词的 txt 中查找一个值,第一个单词的长度必须大于 10。我希望我的结果与结果一起打印,并且我的结果所在的行。

I can find a value that first word is len>10, however I can't print the line number that my result is on, I've tried readline() , and it comes with error like AttributeError: 'list' object has no attribute 'readline'我可以找到第一个单词是 len>10 的值,但是我无法打印我的结果所在的行号,我尝试过readline() ,它带有类似AttributeError: 'list' object has no attribute 'readline'

Here is my code:这是我的代码:

for line in open("birds.txt"):
  a = line.strip()
  word = a.split()
    if len(word[0])>10:
    c = word.readline()
print(a + " : " +c)

This is what your code would look like:这就是您的代码的样子:
use with as a context manager so that the opened file would be closed at the end of operations ( in your case you're not closing the file, it's a bad practice).使用with作为上下文管理器,以便在操作结束时关闭打开的文件(在您的情况下,您没有关闭文件,这是一种不好的做法)。
To get the index AND the content at the same time you should use enumerate .要同时获取索引和内容,您应该使用enumerate
finally if you're using python > 3.6 you should use string formatting instead of concatenation since it's clearer and could lead to performance gains.最后,如果您使用 python > 3.6,您应该使用字符串格式而不是串联,因为它更清晰并且可能会带来性能提升。

with open("birds.txt") as f:
    for index,line in enumerate(f):
        words = line.strip().split()
        if len(words[0])>10:
            print(f'{index} : {words[0]}')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM