2012-10-27 84 views
0

我正在尝试创建一个程序来搜索我在单独文档中的文章。我无法让我的程序搜索该术语并允许我查看仅包含搜索术语的文档。理想情况下,我希望搜索输入像月亮一样,并允许我访问该文档。完整的文档看起来像这样,我的代码如下。从python中的外部文件搜索和检索文件

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

回答

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