在文本文件中查找行

时间:2015-11-14 20:46:25

标签: python list line

您将实现函数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)

3 个答案:

答案 0 :(得分:1)

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

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'])

答案 1 :(得分:0)

未经测试但应该可以使用

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"])

答案 2 :(得分:0)

这个例子怎么样:

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')

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

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

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)