2014-12-04 6 views
0

설정 파일에서 목록/튜플을 동적으로로드하고 싶습니다.Python이 설정 파일에서 튜플 /리스트를 동적으로로드합니다.

웹 사이트를 크롤링하는 크롤러를 작성해야하지만 페이지가 아닌 발견 된 파일을 알고 싶습니다.

나는 다음과 같이 사용자가 settings.py 파일과 같은 파일 형식을 지정할 수 있습니다 :

# Document Types during crawling 
textFiles = ['.doc', '.docx', '.log', '.msg', '.pages', '.rtf', '.txt', '.wpd', '.wps'] 
dataFiles = ['.csv', '.dat', '.efx', '.gbr', '.key', '.pps', '.ppt', '.pptx', '.sdf', '.tax2010', '.vcf', '.xml'] 
audioFiles = ['.3g2','.3gp','.asf','.asx','.avi','.flv','.mov','.mp4','.mpg','.rm','.swf','.vob','.wmv'] 


#What lists would you like to use ? 
fileLists = ['textFiles', 'dataFiles', 'audioFiles'] 

은 내가 crawler.py

내 설정 파일을 가져 내가 HTML 콘텐츠의 링크를 찾을 수 beautifulsoup 모듈을 사용 다음과 같이 처리하십시오.

for item in soup.find_all("a"): 
      # we dont want some of them because it is just a link to the current page or the startpage 
      if item['href'] in dontWantList: 
       continue 

      #check if link is a file based on the fileLists from the settings 
      urlpath = urlparse.urlparse(item['href']).path 
      ext = os.path.splitext(urlpath)[1] 
      file = False 
      for list in settings.fileLists: 
       if ext in settings.list: 
        file = True 
        #found file link 
        if self.verbose: 
         messenger("Found a file of type: %s" % ext, Colors.PURPLE) 
        if ext not in fileLinks: 
         fileLinks.append(item['href']) 

      #Only add the link if it is not a file 
      if file is not True: 
       links.append(item['href']) 
      else: 
       #Do not add the file to the other lists 
       continue 

다음 코드 세그먼트 오류 :

for list in settings.fileLists: 
       if ext in settings.list: 

분명히 파이썬은 settings.list가 목록이라고 생각하기 때문입니다.

어쨌든 파이썬이 설정 파일의 목록을 동적으로 보도록 지시해야합니까?

+2

자신 만의 변수에'list'라는 이름을 지정하지 마십시오. 또한'set '을 사용하면 멤버쉽 테스트를보다 효율적으로 수행 할 수 있습니다. – jonrsharpe

+0

'settings.list'는 어디에서 왔습니까? –

+0

감사합니다. 나는 나의 이름을 개정했다. 내 IDE 정말 그것에 대해 행복하지 않았다 :) – Richard

답변

1

나는 당신을 위해 무엇을 찾고있는 것은 대신이라고 생각 : 당신이 필요로하는

if ext in settings.list: 

ext_list = getattr(settings, list) 
if ext in ext_list: 

편집 : 나는 목록 일에 jonrsharpe에 동의, 그래서 나는 그것을 이름을 변경 내 코드