简体   繁体   English

搜索文本文件并打印行号

[英]Searching a text file and printing line numbers

How do you get your function to find the lines in the text file where the word occurs and print the corresponding line numbers? 您如何获得函数来查找文本文件中出现单词的行并打印相应的行号?

I had to open a text file with the paragraph and then am supposed to search the paragraph for certain words and then print the specific line numbers for the words. 我必须打开带有段落的文本文件,然后应该在段落中搜索某些单词,然后为这些单词打印特定的行号。

Here is what I have so far. 这是我到目前为止所拥有的。

words = [network, devices, computer, fire, local, area, room, single]
    def index(string):
       lines = open('Network.txt', 'r')
       string = str(lines.read())
       lines.close()
       return string

Assuming you have opened your file correctly, this is actually quite easy. 假设您已正确打开文件,这实际上很容易。 Using file.read() pulls the entire file in, which you don't want. 使用file.read()可以拉入不需要的整个文件。 If you are doing line-based processing, iterate through the file using with as it make opening, closing and error handling of files much easier: 如果您正在执行基于行的处理,请使用with遍历文件with因为这样可以更轻松地打开,关闭和错误处理文件:

with open(filename) as file:
    for line in file:
        #do something

The core piece with your logic is enumerate() , which takes an iterable and returns a count along with each iterated item. 具有您的逻辑的核心部分是enumerate() ,它需要一个可迭代的并且返回一个计数以及每个被迭代的项。

words = ["word","another"]
for line_num,line in enumerate(file):
    if any([word in line for word in words]):
        print line_num, line

The other factor is the list comprehension which checks if the any word is on a line. 另一个因素是列表理解,它检查任何单词是否在一行上。 The any() function "returns True if any element of the iterable is true". any()函数“如果iterable的任何元素为true,则返回True”。 And the following list comprehension: 以及以下列表理解:

[word in line for word in words]

can be read as: 可以理解为:

[ tell me if word is in the line for each word in all of the words] . [ 告诉我,如果 word in line for 的每个 word in 的所有的 words]

If any word is in that array, ie at least one of your words is the line, its true, and thus will be printed. 如果该数组中有any单词,即您的单词中至少有一个是行,则该单词为真,因此将被打印出来。

Use enumerate and a set union of the line in question if you just want to test for presence of individual words: 如果您只想测试单个单词的存在,请使用enumerate和相关行的集合

words={'some', 'target', 'words', 'in', 'a', 'set'}

with open(f_name) as fin:
    for line_num, line in enuemrate(fin):
        if set(line.split()) & words:
            print(line_num, line)

try this: 尝试这个:

words = []
lines = {}
for i in words:
    lines[i] = []

with open("file", "r") as fin:
    curLine = 0
    for i in fin.readLines():
        for j in words:
            if j in i:
                lines[j].append(curLine)
        curLine += 1

for i in words:
    print lines[j]

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

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