파이썬
텍스트에서 단어 빈도 세기 간단한 예제
콩콩(๓° ˘ °๓)♡
2023. 5. 9. 08:54
1. 텍스트 파일을 읽어 line으로 저장해준다.
wiki=open('wiki.txt',"rt")
lines=wiki.readlines()
line=[]
for i in range(len(lines)):
line.append(lines[i])
wiki.close()
print(line)
2. 불필요한 부분은 제거해준다.
import re
line=re.sub('\n','',line[0])
line
3. 띄어쓰기, 반점, 온점을 기준으로 각각의 단어로 분해해서 wordlist에 담아준다.
wordlist=[]
for word in re.split('[,. ]',line):
if not word:
continue
wordlist.append(word)
wordlist
['As',
'the',
'country',
'became',
'embroiled',
'in',
'a',
'domestic',
'crisis',
'the',
'first',
'government',
'was',
'dislodged',
'and',
'succeeded',
'by',
'several',
'different',
'administrations',
'Bolikango',
'served',
'as',
'Deputy',
'Prime',
'Minister',
'in',
'one',
'of',
'the',
'new',
'governments',
'before',
'a',
'partial',
'state',
'of',
'stability',
'was',
'reestablished',
'in',
'1961',
'He',
'mediated',
'between',
'warring',
'factions',
'in',
'the',
'Congo',
'and',
'briefly',
'served',
'once',
'again',
'as',
'Deputy',
'Prime',
'Minister',
'in',
'1962',
'before',
'returning',
'to',
'the',
'parliamentary',
'opposition',
'After',
'Joseph-Desire',
'Mobutu',
'took',
'power',
'in',
'1965',
'Bolikango',
'became',
'a',
'minister',
'in',
'his',
'government',
'Mobutu',
'soon',
'dismissed',
'him',
'but',
'appointed',
'him',
'to',
'the',
'political',
'bureau',
'of',
'the',
'Mouvement',
'Populaire',
'de',
'la',
'Revolution',
'Bolikango',
'left',
'the',
'bureau',
'in',
'1970',
'He',
'left',
'Parliament',
'in',
'1975',
'and',
'died',
'seven',
'years',
'later',
'His',
'grandson',
'created',
'the',
'Jean',
'Bolikango',
'Foundation',
'in',
'his',
'memory',
'to',
'promote',
'social',
'progress',
'The',
'President',
'of',
'the',
'Congo',
'posthumously',
'awarded',
'Bolikango',
'a',
'medal',
'in',
'2005',
'for',
'his',
'long',
'career',
'in',
'public',
'service']
4. for문으로 전체를 순회하며 각각의 단어를 count 딕셔너리의 키로 담아주고 값에 단어의 개수가 세어지도록 한다.
그리고 딕셔너리의 키와 값을 items()함수로 (키, 값) 튜플로 받아 sorted() 함수와 람다를 이용해 값을 기준으로 빈도가 높은 순으로 정렬, 슬라이싱으로 빈도수 상위 10개를 프린트한다.
count={}
for word in wordlist:
if word not in count:
count[word]=1
else:
count[word]+=1
for (k,v) in sorted(count.items(), key=lambda x:x[1], reverse=True)[:10]:
print(k,v)
in 12
the 10
Bolikango 5
a 4
of 4
and 3
to 3
his 3
became 2
government 2