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

2024-06-01 00:41:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

有人知道我如何从stringList而不是任何stringprint匹配string吗?你知道吗

提前谢谢。你知道吗


Tags: intxtforstringlineopenutf8encoding
2条回答

不知道是什么唯一.txt看来你可以把你的窝藏起来

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)

您可以使用以下技巧完成此操作:

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

相关问题 更多 >