在文本文件中查找行

Find the lines in the text file

您将实现函数 index(),它将文本文件的名称和单词列表作为输入。对于列表中的每个单词,您的函数将在文本文件中找到该单词出现的行并打印相应的行号(编号从 1 开始)。您应该只打开并阅读文件一次。

我只数过一次。

def index(filename, words):
    infile = open(filename)
    content = infile.readlines()
    infile.close()
    count = {}
    for word in words:
        if word in count:
            count[word] += 1
        else:
            count[word] = 1
        for word in count:
            print('{:12}{},'.format(word, count[word]))

    Output :index('raven.txt',['raven'])
        raven       1,
    Desired Output : index('raven.txt',['raven'])
       raven 44, 53, 55, 64, 78, 97, 104, 111, 118, 12(No of lines it appear)

未测试但应该有效

def index(filename, words):
    with open(filename, "r") as f:
        for i, line in enumerate(f):
            for word in words:
                if word in line:
                    return "%s at line %i" % (word, i + 1)

print index("some_filename", ["word1", "word2"])

或者避免嵌套 for 循环:

def index(filename, words):
    with open(filename, "r") as f:
        for line, word in itertools.product(enumerate(f), words):
            if word in line[1]:
                return "%s at line %i" % (word, line[0] + 1)

print index("some_filename", ["word1", "word2"])

并使用列表理解:

def index(filename, words):
    with open(filename, "r") as f:
        return "\n".join("%s at line %i" % (word, line[0] + 1) for line, word in itertools.product(enumerate(f), words) if word in line[1])

print index("some_filename", ["word1", "word2"])

这个例子怎么样:

File1.txt

Y
x
u
d
x
q

代码:

word='x'
i = 0
with open('file1.txt', 'r') as file:
    for line in file:
        i = i +1
        if word in line:
            print(i)
            print('Found It')

在本例中,您读入了一个文件,并逐行查看它。在每一行中,您都会查看是否存在单词。如果是这种情况,我们会在屏幕上打印一些东西。

编辑:
或者在定义中它将是:

filename='file1.txt'
word='x'
def index(filename, word):
    i = 0
    with open(filename, 'r') as file:
        for line in file:
            i = i +1
            if word in line:
                print(i)
                print('Found It')

index(filename, word)

可能遇到了同样的问题..我写了下面的..

def index(filename, lst):
    infile = open(filename, 'r')
    content = infile.readlines()
    infile.close()

    for word in lst:
        print(word, end = '\t')
        for line in range(len(content)):
            if word in content[line]:
            print(line+1, end= ' ')
        print()

index('raven.txt', ['raven'])