简体   繁体   中英

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.

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)

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

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.

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

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