代码之家  ›  专栏  ›  技术社区  ›  helpermethod

消除重复-我要用一套吗?

  •  1
  • helpermethod  · 技术社区  · 14 年前

    set ?

    我想到了这样的事情:

    def geturls(filename)
      f = open(filename)
      s = set() # creates an empty set?
    
      for line in f:
        # see if the line matches some regex
    
        if match:
          s.add(match.group(1))
    
      f.close()
    
      return sorted(s)
    

    编辑

    编辑2

    10.254.254.28--[06/Aug/2007:00:12:20-0700]“获取 /凯瑟/22300/HTTP/1.0“302 528”-” “Mozilla/5.0(X11;U;Linux i686 (x86_64);美国标准;rv:1.8.1.4) 壁虎/20070515火狐/2.0.0.4“ 10.254.254.58--[06/Aug/2007:00:10:05-0700]“获取 “谷歌机器人mscrawl moma(企业; 棒XYZ; 10.254.254.28--[06/Aug/2007:00:11:08-0700]“获取 /favicon.ico HTTP/1.0“302 3404”-” “谷歌机器人mscrawl moma(企业;

    有趣的部分是GET和HTTP之间的url。也许我应该说这是练习的一部分 没有真实世界的数据

    5 回复  |  直到 14 年前
        1
  •  4
  •   SilentGhost    14 年前
    def sorted_paths(filename):
        with open(filename) as f:
           gen = (matches(line) for line in f)
           s = set(match.group(1) for match in gen if match)
        return sorted(s)
    
        2
  •  3
  •   fas    14 年前

    这是一个很好的方法,无论是在性能方面还是在简洁性方面。

        3
  •  2
  •   Ignacio Vazquez-Abrams    14 年前

    只有顺序无关紧要(因为集合是无序的),并且类型是可散列的(哪些字符串是散列的)。

        4
  •  0
  •   Tony Veijalainen    14 年前

    只有在任何地方都应该有完整的路径名,如果在Windows中,名称可以是不同的大小写,因为它们不区分大小写。同样在Python中,您也可以使用/而不是\(是:小心地转义反斜杠)。

    http://www.domain.com 意思是一样的,你应该停止如何正常化。

        5
  •  0
  •   ghostdog74    14 年前

    你可以用字典来存储你的路径。

    from collections import defaultdict
    h=defaultdict(str)
    uniq=[]
    for line in open("file"):
        if "pattern" in line:
           # code to extract path here.
           extractedpath= ......
           h[extractedpath.strip()] = "" #using dictionary to store unique values
           if extractedpath not in uniq:
               uniq.append(extractedpath) #using a list to store unique values