【问题标题】:Printing in which list or dictionary the word is located in打印单词所在的列表或字典
【发布时间】:2015-03-24 01:46:08
【问题描述】:

我有一个包含以下内容的文本文件:

<NEW DOCUMENT>
Look on the bright 
side of Life.
<NEW DOCUMENT>
look on the very, dark
side of the Moon
<NEW DOCUMENT>
is there life
on the moon

我正在尝试创建一个 python 脚本,可以将其拆分为多个“文档”,然后搜索它们,如果我搜索月亮这个词,那么它应该告诉我它在第二个和第三个文档中找到。在寻求帮助后,我设法让它打印出它在其中找到单词的行,但它没有打印出它所在的文档(我正在尝试实现它,但它对我来说效果不佳)。

非常感谢任何帮助!

到目前为止的代码如下:

def main():
    docs=[]
    with open("ap_docs2.txt") as f:
        lines = f.read().split("<NEW DOCUMENT>")[1:]
        for x in lines:
            docs.append(x.strip())
        numOfDocs=len(docs)
        docs1 = map(str.lower, docs) ## Convert list to lower case for search
        print (docs)
        print("Number of Documents:",numOfDocs)

    search = input("Enter search words: ")
    for x in docs1:
        if search in x:
            print ("{} found in:\t {}".format(search,x))

main()

【问题讨论】:

  • 您能否包含一个未显示文档名称的 docs1search 元素示例。
  • this question的可能重复?

标签: python list search python-3.x dictionary


【解决方案1】:

这是否符合您的要求?我只是打印文档中匹配行的索引。

def main():
    docs=[]
    with open("ap_docs2.txt") as f:
        lines = f.read().split("<NEW DOCUMENT>")[1:]
        for x in lines:
            docs.append(x.strip().lower())
        numOfDocs=len(docs)
        print (docs)
        print("Number of Documents:",numOfDocs)

    search = input("Enter search words: ")
    for x in docs:
        if search in x:
            print('Found in document %d' % (docs.index(x) + 1))

main()

【讨论】:

    猜你喜欢
    • 2017-07-02
    • 2017-07-18
    • 2016-09-03
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多