2012-11-22 3 views
0

URL을 가져 와서 텍스트를 구문 분석 한 다음 위젯을 검색하는 코드 스 니펫이 있습니다. 위젯을 감지하는 방법은 단어 widget1을 찾은 다음 위젯의 끝을 나타내는 endwidget을 찾습니다.파일에 쓰고 이상한 들여 쓰기 받기

기본적으로 코드는 단어 widget1을 찾고 endwidget으로 끝나면 텍스트의 모든 줄을 파일에 씁니다. 그러나 내 코드 첫 번째 widget1 줄 뒤에 모든 줄 들여 쓰기입니다. 왜이 들여 쓰기를 얻고있다

widget1 this is a really cool widget 
it does x, y and z 
and also a, b and c 
endwidget 

:

이 내가이 원하는 것은 내 출력

widget1 this is a really cool widget 
     it does x, y and z 
     and also a, b and c 
     endwidget 

입니까? 이

for url in urls: 
     page = mech.open(url) 
     html = page.read() 
     soup = BeautifulSoup(html) 
     text= soup.prettify() 
     texts = soup.findAll(text=True) 

     def visible(element): 
      if element.parent.name in ['style', 'script', '[document]', 'head', 'title']: 
      # If the parent of your element is any of those ignore it 

       return False 

      elif re.match('<!--.*-->', str(element)): 
      # If the element matches an html tag, ignore it 

       return False 

      else: 
      # Otherwise, return True as these are the elements we need 

       return True 

     visible_texts = filter(visible, texts) 

     inwidget=0 
     # open a file for write 
     for line in visible_texts: 
     # if line doesn't contain .widget1 then ignore it 
      if ".widget1" in line and inwidget==0: 
       match = re.search(r'\.widget1 (\w+)', line) 
       line = line.split (".widget1")[1] 
       # make the next word after .widget1 the name of the file 
       filename = "%s" % match.group(1) + ".txt" 
       textfile = open (filename, 'w+b') 
       textfile.write("source:" + url + "\n\n") 
       textfile.write(".widget1" + line) 
       inwidget = 1 
      elif inwidget == 1 and ".endwidget" not in line: 
       print line 
       textfile.write(line) 
      elif ".endwidget" in line and inwidget == 1: 
       textfile.write(line) 
       inwidget= 0 
      else: 
       pass 

답변

1

이유 첫 번째는 제외한 모든 줄이 들여 쓰기를 받고있어 첫 번째 줄은 textfile.write(".widget1" + line)으로 줄을 편집하기 때문에 나머지 줄은 들여 쓰기가있는 html 파일에서 직접 가져옵니다. 줄에 str.strip()을 사용하고 textfile.write(line)textfile.write(line.strip())으로 변경하여 원하지 않는 공백을 제거 할 수 있습니다.

0

을 수행하여 원하는 출력으로 출력에서 ​​이동하려면 ... 내 코드이 :

#a is your output 
a= '\n'.join(map(lambda x: x.strip(),a.split('\n'))) 
+0

감사합니다.''는'texts' 변수이거나 각각'visible_texts의 줄'입니까 – user1328021

+0

또한 정확히 무엇을하고 있습니까? 그것은 캐리지 리턴을 제거하고 그 밖의 무엇입니까? – user1328021

+0

\ n을 사용하여 각 줄마다 문자열 목록을 만든 다음 각 줄을 제거합니다. 즉, 처음과 마지막에 공백을 제거하지만 줄 바꿈 만하면 해당 줄을 지울 수 있습니다. lstrip로 시작) 문자열은 \ n을 구분 기호로 사용하여 다시 결합됩니다. – LtWorf

관련 문제