【问题标题】:How to check whether a line contains string from list and print the matched string如何检查一行是否包含列表中的字符串并打印匹配的字符串
【发布时间】:2019-07-30 01:31:49
【问题描述】:
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")

有谁知道我如何将printstringList 匹配的string 匹配,而不是任何string

提前致谢。

【问题讨论】:

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


    【解决方案1】:

    在不知道 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】:

    首先,我鼓励您在 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}")
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        您可以通过以下技巧做到这一点:

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

        【讨论】:

          猜你喜欢
          • 2015-07-27
          • 1970-01-01
          • 2013-01-01
          • 2020-02-26
          • 1970-01-01
          • 2022-12-12
          • 2010-10-04
          • 2019-04-11
          • 1970-01-01
          相关资源
          最近更新 更多