파이썬 웹크롤링 에러문제

조회수 1343회
import requests

from bs4 import BeautifulSoup

import operator

def start(url):
     word_list=[]
    source_code=requests.get(url).text
    soup=BeautifulSoup(source_code,'lxml')
    p_tag=soup.findAll('p',{'class':'tt-post-title'})

    for title_text in p_tag:
        content = title_text.text
        words=content.lower().split()
        for each_word in words:
            word_list.append(each_word)
    clean_up_list(word_list)

def clean_up_list(word_list):
    clean_up_list=[]
    for word in word_list:
        symbols="`~!@#$%^&*()-=_+[]\{}|;',./:\"<>?"
        for i in  range(0,len(symbols)):
            word = word.replace(symbols[i],"")
        if len(word)>0:
        #    print(word)
            clean_word_list.append(word)

    create_dictionary(clean_word_list)

def create_dictionary(clean_word_list):
    word_count={}
    for word in clean_word_list:
        if word in word_count:
            word_count[word] +=1
        else:
            word_count[word]=1
    for key, value in sorted(word_count.items(),key=operator.itemgetter(1)):
        print(key,value)

start('https://creativeworks.tistory.com')

티스토리 블로그 따라서 파이썬 공부중인 학생입니다. 코딩중에 원인을 모를 에러가 발생해서 질문올립니다. 코드는 위와 같습니다 현재 MAC 에서 코딩을하고 ATOM IDE 를 이용중입니다. 파이썬 버전은 3.7.1 입니다. 위 코드를 컴파일 했을시

Traceback (most recent call last):
  File "/Users/stronghu/Documents/test36.py", line 44, in <module>
    start('https://creativeworks.tistory.com')
  File "/Users/stronghu/Documents/test36.py", line 19, in start
    clean_up_list(word_list)
  File "/Users/stronghu/Documents/test36.py", line 31, in clean_up_list
    create_dictionary(clean_word_list)
NameError: name 'clean_word_list' is not defined

이런 에러를 발생 합니다. create_dictionary(clean_word_list)가 원래는 for 문 밖에 서 실행이 되어야 해서 위 코드와 같이 코딩을 했는데 create_dictionary(clean_word_list) 문이 for문 안으로 들어가면 문제 없이 컴파일이됩니다 왜그런지 이유를 아무리 생각해도 이해가 되질 않습니다.

2 답변

  • 좋아요

    0

    싫어요
    채택 취소하기
    1. 링크를 열어봤고 질문자님이 잘못 받아적으신 게 맞습니다. 링크된 소스에서는 clean_up_list() 메소드에서 clean_word_list 리스트를 정의하고 있습니다. 그런데 올려 주신 소스 보면 질문자님은 clean_up_list 리스트를 정의하고 계시고요. (이래서 코드를 스크린샷으로 올리지 말자는 건데 말입니다.)
    2. for 안으로 넣으면 컴파일이 되느냐? 그 for 안의 if 아래에 clean_word_list가 있기는 있기 때문입니다. 아마 실행하면 에러가 나든지 원하는 동작을 안 하겠지만요.

    예제 코드를 일점 일획도 틀림없이 그대로 받아적어 따라해 보신 다음, 그래도 문제가 생기면 그때는 그 예제를 만드신 분께 먼저 질문해 봐 주시면 좋을 것 같습니다.

    • 예제를 너무 맹신 했던것 같습니다. 앞으로는 주의 하겠습니다. 문제 해결에 도움을 주셔서 감사합니다. 시티젠 2018.12.27 14:43
    • 잘못은 저예제 만든사람이 잘못이죠 ㅎ 그냥 쭉 복사할 수 있게 텍스트로 올려주면 되는걸 굳이 스샷으로 올려서~ 엽토군 2018.12.27 15:03
  • def clean_up_list(word_list):
        clean_up_list=[]
        for word in word_list:
            symbols="`~!@#$%^&*()-=_+[]\{}|;',./:\"<>?"
            for i in  range(0,len(symbols)):
                word = word.replace(symbols[i],"")
            if len(word)>0:
            #    print(word)
                clean_word_list.append(word)
    

    상기 함수에서 clean_word_list 는 없는 객체입니다.

    clean_up_list 에 append 하려고 한 건 아닌가요?

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)