我正在尝试创建一个程序,用于搜索我在单独文档中的文章。我无法让我的程序搜索该术语,并允许我查看仅包含搜索词的文档。理想情况下,我希望搜索输入类似于月亮,并允许我访问该文档。完整的文档看起来像这样,我的代码如下。
<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)
答案 0 :(得分: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