如何检查行是否包含列表中的字符串并打印匹配的字符串

时间:2019-03-08 02:53:16

标签: python python-3.x python-2.7

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

有人知道我如何print而不是stringstringList的匹配string吗?

谢谢。

4 个答案:

答案 0 :(得分:3)

在不知道unique.txt看起来像什么的情况下,听起来好像可以嵌套for和

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)

答案 1 :(得分:2)

您可以使用以下技巧来做到这一点:

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

答案 2 :(得分:1)

您还可以使用集合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

注意:但是,如果有多个匹配项,这并不说明事实。

答案 3 :(得分:0)

首先,我建议您使用with来打开文件,并避免在某些时候程序崩溃的问题。其次,您可以应用filter。最后,如果您使用的是Python 3.6+,则可以使用f字符串。

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