Reputation: 131
stringList = {"NppFTP", "FTPBox" , "tlp"}
uniqueLine = open('unique.txt', 'r', encoding='utf8', errors='ignore')
for line in uniqueLine:
if any(s in line for s in stringList):
print ("match found")
Does anyone know how can I print
the matched string
from stringList
rather than any string
?
Thanks in advance.
Upvotes: 2
Views: 134
Reputation: 409
Without knowing what unique.txt looks like it sounds like you could just nest your for and if
stringList = {"NppFTP", "FTPBox" , "tlp"}
uniqueLine = open('unique.txt', 'r', encoding='utf8', errors='ignore')
for line in uniqueLine:
for s in stringList:
if s in line:
print ("match found for " + s)
Upvotes: 3
Reputation: 69755
First, I encourage you to use with
in oder to open a file, and avoid issues if your program crashes at some point. Second, you can apply filter
. Last, if you are using Python 3.6+, you can use f-strings.
stringList = {"NppFTP", "FTPBox" , "tlp"}
with open('unique.txt', 'r', encoding='utf8', errors='ignore') as uniqueLine:
for line in uniqueLine:
strings = filter(lambda s: s in line, stringList)
for s in strings:
print (f"match found for {s}")
Upvotes: 0
Reputation: 14216
You can also use set intersections
stringList = {"NppFTP", "FTPBox" , "tlp"}
uniqueLine = open('unique.txt', 'r', encoding='utf8', errors='ignore')
for line in uniqueLine:
found = set(line) & stringList
if found:
print("Match found: {}".format(found.pop()))
else:
continue
Note: This doesn't account for the fact if there is more than one match however.
Upvotes: 1
Reputation: 2522
You can do this with the following trick:
import numpy as np
stringList = {"NppFTP", "FTPBox" , "tlp"}
uniqueLine = open('unique.txt', 'r', encoding='utf8', errors='ignore')
for line in uniqueLine:
# temp will be a boolean list
temp = [s in line for s in stringList]
if any(temp):
# when taking the argmax, the boolean values will be
# automatically casted to integers, True -> 1 False -> 0
idx = np.argmax(temp)
print (stringList[idx])
Upvotes: 2