简体   繁体   中英

Trying to save keywords from a .txt file to an array and use that array to search another doc for the keywords

I am trying to save a bunch of keywords in a file called keywordtest.txt containing words such as networkmanager , filemanager and speaker etc. (Each on its own line in the .txt file).

I have got it to save the words into an array but I then want it to use the words stored in that array to search in another document called test and bring up the whole line that the keywords was found in and store that line in another doc called results.txt.

I have managed to get it to search using the words in the array and save them to another file but will only find something if it is not contained in a line:

For example, I search for networkmanager and if it is just networkmanager on a line of its own in the file I am searching in it will find it, but if its like 'I am a networkmanager' for example it wont pick it up.

#!\usr\bin\python

x = []

with open("keywordtest.txt","r") as y:
    for line in y:
        x.append(line)
print x

theFile = open ("results.txt", "w")
searchfile = open("test", "r")

for line in searchfile:
    for word in x: 
    if word in line: 
    theFile.write(line)

theFile.close()
searchfile.close()

EDIT: the code i posted was a version of me when trying something out, i seen online someone using 'word' instead of 'line' in some places and tried it out but it didnt like it, the code below is the code i have got to work but only displays the ekywords i am searching for if they are on their own.

#!\usr\bin\python

x = []

with open("keywordtest.txt","r") as y:
    for line in y:
        x.append(line)
print x


theFile = open ("results.txt", "w")
searchfile = open("test", "r")

for line in searchfile:
    if line in x: theFile.write(line)
    if line in x: print line

theFile.close()
searchfile.close()
    #!\usr\bin\python

x = []

with open("keywordtest.txt","r") as y:
    for line in y:
        x.append(line)
print x

theFile = open ("results.txt", "w")
searchfile = open("test.txt", "r")

for line in searchfile:
    for word in x: 
        if word in line.strip():
            theFile.write(word)

theFile.close()
searchfile.close()

based on your edit:

#!\usr\bin\python
x = []

with open("keywordtest.txt","r") as y:
    for line in y:
        x.append(line)
print x


theFile = open ("results.txt", "w")
searchfile = open("test.txt", "r")

for line in searchfile:
    for item in x:
        if item in line: 
            theFile.write(line)
            print line

theFile.close()
searchfile.close()

This saves the matched words in theFile.txt and will print out the matches assuming keywordtest.txt has only one word per line same as test.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM