2016-10-16 2 views
0

아래 코드의 목적은 매년 범위 내에서 "발명 된"단어에 대한 옥스포드 영어 사전의 웹 스크랩입니다. 이것은 모두 의도 한대로 작동합니다.주어진 범위에 대해이 행을 모두 CSV 파일에 쓰려면 어떻게해야합니까?

import csv 
import os 
import re 
import requests 
import urllib2 

year_start= 1550 
year_end = 1552 
subject_search = ['Law'] 

for year in range(year_start, year_end +1): 
    path = '/Applications/Python 3.5/Economic' 
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) 
    urllib2.install_opener(opener) 

    user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' 
    header = {'User-Agent':user_agent} 

    resultPath = os.path.join(path, 'OED_table.csv') 
    htmlPath = os.path.join(path, 'OED.html') 
    request = urllib2.Request('http://www.oed.com/search?browseType=sortAlpha&case-insensitive=true&dateFilter='+ str(year)+ '&nearDistance=1&ordered=false&page=1&pageSize=100&scope=ENTRY&sort=entry&subjectClass='+ str(subject_search)+ '&type=dictionarysearch', None, header) 
    page = opener.open(request) 

    with open(resultPath, 'wb') as outputw, open(htmlPath, 'w') as outputh: 
     urlpage = page.read() 
     outputh.write(urlpage) 

     new_words = re.findall(r'<span class=\"hwSect\"><span class=\"hw\">(.*?)</span>', urlpage) 
     print new_words 
     csv_writer = csv.writer(outputw) 
     if csv_writer.writerow([year] + new_words): 
      csv_writer.writerow([year, word]) 

그러나 코드를 실제로 실행하면 csv 파일에 쓰여지는 부분이 내가 말하는 지난 해입니다. 그래서, 내 CSV 파일은 다음과 같은 하나의 행처럼 보이는 끝 :

1552

, 단어 1, word2, word3, 등 ....

나는 기본적으로 범위에서 매년 별도의 행을 갖고 싶어

년. 어떻게해야합니까? 당신은 루프 코드를 실행할 때마다에 덮어 쓰기를 계속

답변

1

, 루프 밖에서 한 번 열고 그래서 코드를 실행할 때마다 기존 데이터에없는 추가합니다 a 대신 w의 사용하여 파일 열기에를 추가 덮어 썼습니다. :

with open("/Applications/Python 3.5/Economic/OED_table.csv", 'a') as outputw, open("/Applications/Python 3.5/Economic/OED.html", 'a') as outputh:  
    for year in range(year_start, year_end +1): 
     ..................... 
+1

고맙습니다.이 점이 저를 위해 고맙습니다. – Kainesplain

관련 문제