Skip to main content
 首页 » 编程设计

python之消除重复——我应该使用一套吗

2025年05月04日12dudu

我需要通读一个日志文件,提取所有路径,并返回一个不包含重复路径的排序列表。最好的方法是什么?使用集合?

我想过这样的事情:

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] "GET /keyser/22300/ HTTP/1.0" 302 528 "-" "Mozilla/5.0 (X11; U; Linux i686 (x86_64); en-US; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4" 10.254.254.58 - - [06/Aug/2007:00:10:05 -0700] "GET /edu/languages/google-python-class/images/puzzle/a-baaa.jpg HTTP/1.0" 200 2309 "-" "googlebot-mscrawl-moma (enterprise; bar-XYZ; foo123@google.com,foo123@google.com,foo123@google.com,foo123@google.com)" 10.254.254.28 - - [06/Aug/2007:00:11:08 -0700] "GET /favicon.ico HTTP/1.0" 302 3404 "-" "googlebot-mscrawl-moma (enterprise; bar-XYZ;

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

请您参考如下方法:

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)