Programming

파이썬 단어 빈도수 카운트 알고리즘 (자세한 설명)

김봉철 2021. 11. 3. 22:00

 일정 텍스트 파일에서 단어 중복 횟수, 단어 빈도수를 측정하는 코드이다.

 try, except를 사용했다. 따로 함수도 있는 것 같은데, 함수로 쉽게 쉽게 하는 건 공부하는 느낌이 안들어서.. 별로 안 좋아한다. 그래서 이 방법을 사용했다.

 

 내가 공부하며 헷갈리는 부분이 많아서 진짜 자세하게 풀어서 설명했다. 단당류 수준으로...!

 

 사실 헷갈릴 부분이 없는 것 같기도 한데, 내가 자료형의 개념이 정확하게 잡혀있지 않아서 헷갈린 것 같다.

back to the basic!

코드

fname = "ex.txt"
hand = open(fname, 'r')
stc = hand.read()
wds = stc.split()

dic = dict()
for wd in wds:
    try: dic[wd] = dic[wd] + 1
    except: dic[wd] = 1

print(dic)

출력

{'the': 6, 'clown': 2, 'ran': 2, 'after': 1, 'car': 3, 'and': 3, 'ther': 1, 'into': 1, 'tent': 2, 'fell': 1, 'down': 1, 'on': 1}

 

ex.txt

the clown
ran after the car and ther car ran into the tent and the
tent fell down on the clown and the car

 

코드 설명

fname= "ex.txt"
 #작업할 텍스트 파일 지정.
 #실행하는 코드 파일과 같은 디렉토리에 있어야 함.
hand = open(fname, 'r')
 #파일 열기
 #hand는 텍스트(x), 텍스트 파일 자체(o).
 #type(hand) >>> <class '_io.TextIOWrapper'>
stc = hand.read()
 #파일 읽기
 #stc는 string 형식.
wds = stc.split()
 #문자열을 끊기.
 #list 형식으로 저장. (중복 o)

dic = dict()
 #dictionary형 변수 선언
for wd in wds:
    try: dic[wd] = dic[wd] + 1
    except: dic[wd] = 1
 #wds의 단어를 dic의 key 값에 하나씩 추가.
 #중복 단어 > try 실행 > 중복된 단어(key)의 value 값 1 증가
 #신규 단어 > except 실행 > dic에 ['wd', 1] 추가

print(dic)