Md Sajid
Md Sajid

Reputation: 131

How to check whether a line contains string from list and print the matched string

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

Answers (4)

rhedak
rhedak

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

lmiguelvargasf
lmiguelvargasf

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

gold_cy
gold_cy

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

Hemerson Tacon
Hemerson Tacon

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

Related Questions