获取文件中出现单词的行?

2024-04-26 21:05:33 发布

您现在位置:Python中文网/ 问答频道 /正文

下面引用的是我的问题。我能够得到所示的输出,但我无法得到前面的数字,如问题中出现的单词出现在。你知道吗

Write a function definition for the following function and then invoke the function to test it works. The function:

search_file(filename, searchword)

should accept a filename (a file fields.txt has been provided on Moodle) and a user specified search word. It searches every line in the file for an occurrence of the word and if it exists it prints out the line preceded by the line number. Importantly it also writes the same output out to a file called fieldsModified.txt.

例如:

search_file("Fields-of-Athenry", "watched")

以上输出应采用以下格式:

9 - Where once we watched the small free birds fly.
21 - Where once we watched the small free birds fly.
26 - She watched the last star falling
33 - Where once we watched the small free birds fly."

Tags: andthefreesearchlineitfunctionwhere
2条回答

试试这个:

def search_file(filename, searchword):
    lines = [line.rstrip('\n') for line in open(filename)]

    lineCount = 1
    results = []
    for line in lines:

        if searchword in line:
            results.append(str(lineCount) + "-" + line)
        lineCount += 1

    with open('fieldsModified.txt', 'w') as f:
        for item in results:
            f.write("%s\n" % item)

    for each in results:
        print(each)


search_file('fields.txt', 'watched')

有多种方法可以做到这一点;我认为这是最直接的:

def search_file(filename, searchword):
    my_file = open(filename)
    output_file = open('fieldsModified.txt', 'w+')

    for i, line in enumerate(my_file):
        if searchword in line:
            print( str(i) + ' - ' + line )
            output_file.write( str(i) + ' - ' + line )

    my_file.close()
    output_file.close()

这是否适合你的需要取决于你需要搜索的文件有多大,你是否关心大小写等。我不确定这是否直接解决了你的问题,所以如果我错过了你想问的问题,请这么说。。。你知道吗

相关问题 更多 >