본문 바로가기
python/python 수업

딕셔너리 key/value 로 정렬

by sj0020 2020. 9. 8.

https://m.blog.naver.com/PostView.nhn?blogId=moonsoo5522&logNo=220826171626&proxyReferer=https:%2F%2Fwww.google.com%2F

 

파이썬 딕셔너리 정렬하기

간혹 딕셔너리에 입력된 key, value 데이터들을 정렬하고 싶어지거나, 꼭 정렬해야 할 때가 있다. 그럴 땐,...

blog.naver.com

논문에서 쓰인 단어의 빈도 수 카운트
= 가장 많이 쓰인 단어부터 10개를 시각화

1. 파일 열기 -> 읽기
2. 가장 많이 쓰인 단어를 찾는다
    1) 단어단위 split (★split 기준)
    2-1) count (★라이브러리 사용)
    2-2) for문
           dict key 누적 (코드)
3. ex) a : 20, c : 40, b : 50
    sort (오름차순 -> 내림차순 key X value!)
* list는 필요하면 하시면 됩니다.
4. 정리된 dict key -> value 출력
    논문에서 많이 출력된 단어는 {key}이고
    {value}번 출력되었습니다.

key = 10 / value = 10
for key, value in dic.items() :
  if value == x :
    print key value

 

import re
import operator
import matplotlib.pyplot as plt
import numpy as np

file = open('ICINCO.txt', 'r') #파일 읽기모드로 열기
text = file.read() #파일 읽어서 text에 저장

List = re.findall(r"[\w']+", text) #단어 split \w기준(특문,숫자 제외하고 split)
dic = {} #딕셔너리 dic 선언
print(List)
for word in List : 
  dic[word] = dic.get(word, 0) + 1 #단어가 나올때 마다 해당 단어 value수를 1씩 증가시킴
  keys = sorted(dic.items(), key=operator.itemgetter(1), reverse=True) #value 수 내림차순으로 key 정렬
print(f"가장 많이 출력된 단어는 {keys[0][0]} 이고, {keys[0][1]}번 출력되었다.") # (가장많이 출력된 단어, 그 단어가 나온 횟수) 출력

# ----------------------------------------------

best_word = [] #best_word list 선언
best_word_count = [] #best_word_count list 선언
for x in range(5) :
  best_word.append(keys[x][0]) #가장 많이 나온 단어 5개  리스트 만들기
  best_word_count.append(keys[x][1]) #가장 많이 나온 단어 5개의 갯수 리스트 만들기
print(best_word)
print(best_word_count)

plt.title('paper frequent word') #타이틀이 frequent word 인
plt.bar(range(5), best_word_count,label = 'count num') #막대그래프 만들기
plt.legend() #범례
plt.show() # plot출력

 key=operator.itemgetter(1) - value 기준

 key=operator.itemgetter(0) - key  기준

reverse = true :  내림차순 .  reverse = true 없으면 오름차순으로 정렬됨

 

 

'python > python 수업' 카테고리의 다른 글

dhttest  (0) 2020.09.11
fairytale slicing  (0) 2020.09.08
데이터시각화 matplot weather0106  (0) 2020.09.08
과제 - 생일 일교차  (0) 2020.08.28
weather - colab 최고온도  (0) 2020.08.18