0

我正在尝试创建一个程序来搜索我在单独文档中的文章。我无法让我的程序搜索该词并允许我查看仅包含该搜索词的文档。理想情况下,我希望搜索输入类似于月亮,并允许我访问该文档。完整的文档如下所示,我的代码如下。

<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



search = input("Enter search words: ")
docs = []
document = []
doc_search = []

for line in file2:
    line = line.strip()
    if line == "<NEW DOCUMENT>":
        # start a new document
        document = []
        docs.append(document)
    else:
        # append to the current one
        document.append(line)
docs = ['\n'.join(document) for document in docs]

for line in docs:
    if line == search:
        doc_search = []
        doc_search.append(docs)
4

1 回答 1

2

像这样的东西:

docs=[]
with open("data1.txt") as f:
    lines=f.read().split("<NEW DOCUMENT>")[1:]
    for x in lines:
        docs.append(x.strip())
    print (docs)
search = input("Enter search words: ")   
for x in docs:
    if search in x:
        print ("{} found in:\t {}".format(search,x))

输出:

['Look on the bright \nside of Life.', 'look on the very, dark\nside of the Moon', 'is there life\non the moon']
Enter search words: dark
dark found in:   look on the very, dark
side of the Moon
于 2012-10-27T22:39:42.637 回答