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

问题描述 投票:2回答:4
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而不是任何string stringList匹配的string

提前致谢。

python python-3.x python-2.7
4个回答
3
投票

不知道unique.txt看起来像什么,听起来你可以嵌套你的for和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)

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

1
投票

你也可以使用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

注意:如果有多个匹配,则不会考虑这一事实。


0
投票

首先,我鼓励您在oder中使用with来打开文件,并避免在程序崩溃的情况下出现问题。其次,你可以申请filter。最后,如果您使用的是Python 3.6+,则可以使用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}")
© www.soinside.com 2019 - 2024. All rights reserved.