0

I am trying to create a program that will search through articles that I have in a separate document. I am having trouble getting getting my program to search for the term and allow me to view the documents that contain only the search term. Ideally I want the search input to be something like moon, and allow me to access that document. The full document looks like this, and my code follows.

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

1 Answer 1

2

something like this:

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

output:

['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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.