Python - 从文本文件中查找行号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41429941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:56:11  来源:igfitidea点击:

Python - Find line number from text file

pythonnumbersline

提问by googlecoolcat

I'm writing code that looks in a text file, and sees if the input is in there.

我正在编写在文本文件中查找的代码,并查看输入是否在其中。

E.g.,

例如,

I input "pizza"

我输入"比萨"

My textfile contains:

我的文本文件包含:

bread
pizza
pasta
tomato

Is there a way to print the line number the word pizza is on?

有没有办法打印披萨这个词所在的行号?

采纳答案by Oxymoron88

with open('test.txt') as f:
    content = f.readlines()

index = [x for x in range(len(content)) if 'pizza' in content[x].lower()]

Part (1) of the code reads each line as a separate list in variable "content".

代码的第 (1) 部分将每一行读取为变量“内容”中的单独列表。

Part (2) populates out the line # of content only if 'pizza' exists in that line. [x for x in range(len(content))] simply populates all index values, while 'if 'pizza' in content[x].lower()' keeps the line # that matches the string.

仅当“pizza”存在于该行中时,第 (2) 部分才会填充该行 # 的内容。[x for x in range(len(content))] 只是填充所有索引值,而 'if 'pizza' in content[x].lower()' 保留与字符串匹配的行 #。

回答by Rushy Panchal

There are two ways of accomplishing this:

有两种方法可以实现这一点:

  1. Storing the entire file in memory so you only read it once
  2. Reading through the file on every search, but not having to store it
  1. 将整个文件存储在内存中,以便您只能读取一次
  2. 在每次搜索时通读文件,但不必存储它

For method 1, first read in every line and then get the index that the word is on:

对于方法1,首先读取每一行,然后获取单词所在的索引:

with open('path.txt') as f: data = f.readlines()
line_no = data.index("pizza")

Alternatively, go through the file to find the index:

或者,通过文件查找索引:

with open('path.txt') as f:
    for line_no, line in enumerate(f):
        if line == "pizza":
            break
    else: # for loop ended => line not found
        line_no = -1

回答by Valentin B.

Something like this:

像这样的东西:

import re
import os # You can go without is if you have other means to get your filepath

i = 1
matches = []
target = raw_input("Please type string to match\n")
with open(os.getenv("SOME_PATH") + "/myfile.txt") as fic: # open("myfile.txt") if in your current directory
     for line in fic:
         if re.search(target, line):
             print "Found at line {}".format(i)
             matches.append(i)
         i = i +1
if not len(matches):
    raise Exception, "target not found"

By doing this, you can input a regular expression and it should work (i.e. if you input "p.zza" or "^p.*", it will work.). The list matcheswill contain all indices of lines that match the input pattern.

通过这样做,您可以输入一个正则表达式,它应该可以工作(即,如果您输入“p.zza”或“^p.*”,它就会工作。)。该列表matches将包含与输入模式匹配的所有行索引。

回答by Joran Beasley

print next (i for i,v in enumerate (open (fname),1) if v == needle)