繁体   English   中英

索引和搜索文本文件

[英]Indexing and search in a text file

我有一个包含一本书内容的文本文件。 我想获取此文件并建立一个索引,该索引允许用户搜索文件以进行搜索。

搜索将包括输入单词。 然后,程序将返回以下内容:

  • 包含该词的每一章。
  • 包含单词的行的行号。
  • 单词所在的整行。

我尝试了以下代码:

infile =   open(file)

Dict = {}

word = input("Enter a word to search: ")

linenum = 0
line = infile.readline()
for line in infile
    linenum += 1
    for word in wordList:
        if word in line:
            Dict[word] = Dict.setdefault(word, []) + [linenum]
            print(count, word)
    line = infile.readline()

return Dict

这样的事情行不通,似乎对于处理其他需要处理的模块太尴尬了:

  • 一个“或”运算符来搜索一个或另一个单词
  • “和”运算符可在同一章中搜索一个单词和另一个单词

任何建议都很好。

def classify_lines_on_chapter(book_contents):
    lines_vs_chapter = []
    for line in book_contents:
        if line.isupper():
            current_chapter = line.strip()
        lines_vs_chapter.append(current_chapter)
    return lines_vs_chapter


def classify_words_on_lines(book_contents):
    words_vs_lines = {}
    for i, line in enumerate(book_contents):
        for word in set([word.strip(string.punctuation) for word in line.split()]):
            if word:
                words_vs_lines.setdefault(word, []).append(i)
    return words_vs_lines


def main():
    skip_lines = 93

    with open('book.txt') as book:
        book_contents = book.readlines()[skip_lines:]

    lines_vs_chapter = classify_lines_on_chapter(book_contents)
    words_vs_lines = classify_words_on_lines(book_contents)

    while True:
        word = input("Enter word to search - ")
        # Enter a blank input to exit
        if not word:
            break

        line_numbers = words_vs_lines.get(word, None)
        if not line_numbers:
            print("Word not found!!\n")
            continue

        for line_number in line_numbers:
            line = book_contents[line_number]
            chapter = lines_vs_chapter[line_number]
            print("Line " + str(line_number + 1 + skip_lines))
            print("Chapter '" + str(chapter) + "'")
            print(line)


if __name__ == '__main__':
    main()

此输入文件上尝试一下。 在运行之前,将其重命名为book.txt

暂无
暂无

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

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