인공지능/RNN

자연어 처리 (빈도수) 공부

쿠와와 2020. 11. 21. 17:19
# Day_04_01_freq    빈도를 알아보는 페이지 토큰의 워드 빈도수에 따라서 분류할 수 있음
import nltk
import collections
import matplotlib.pyplot as plt
import operator
# webtext 코퍼스에 있는 wine 파일을 토큰으로 구성하세요
wine = nltk.corpus.webtext.raw('wine.txt')
wine = wine.lower()
tokens = nltk.regexp_tokenize(wine, r'\w+')
# print(tokens[:10])

# print(nltk.corpus.stopwords.fileids())
stopwords = nltk.corpus.stopwords.words('english')  # 불용어(욕 or 사용 x ) 제거
print(stopwords)
# tokens = list(set(tokens) - set(stopwords)) # 내일 문제에 나옴 ㅋㅋ set-> 중복된거 사라짐
tokens = [w for w in tokens if w not in stopwords]  # 불용어 제거
tokens = [w for w in tokens if len(w) > 1]          # 길이가 1인거 제거
# print(tokens[:10])


# 우리가 만든 dictionary
def make_freq_1(tokens):
    freq = {}
    for t in tokens:
        if t in freq:
            freq[t] += 1
        else:
            freq[t] = 1     # key 생성
    return freq


def make_freq_2(tokens):    # 이렇게 쓰기
    freq = {}
    for t in tokens:
        freq[t] = freq.get(t, 0) + 1
    return freq


def make_freq_3(tokens):        # 굉장히 안 좋음
    # return [tokens.count(t) for t in tokens]    # 시간적 문제
    # return [tokens.count(t) for t in set(tokens)]    # 유니크한 토큰으로 만들어줌
    return {t: tokens.count(t) for t in tokens}  # 시간적 문제


def make_freq_4(tokens):        # 가장 많이 나오는 코드
    freq = collections.defaultdict(int)     # 내부적으로 dic를 가지고 있음
    for t in tokens:
        freq[t] += 1
    return freq


# freq1 = make_freq_1(tokens)
# print(freq1)
# freq1 = make_freq_2(tokens)

# 순서 정렬해주는 것
# print(sorted(freq1.items(), key=operator.itemgetter(1), reverse=True))
# freq1 = sorted(freq1.items(), key=lambda freq: freq[1], reverse=True)
# print(freq1)
#
# print(freq1)
# freq1 = make_freq_4(tokens)
# print(freq1)


# 기존에 만들어 진거
# freq1 = collections.Counter(tokens)     # 이것도 많이 씀  dictionary 처럼 작동함
# print(freq1)
# freq1 = make_freq_3(tokens)
# print(freq1)

freq = nltk.FreqDist(tokens)
print(freq)
print(freq['good'])     # dictionary like 처럼 사용 가능
print(freq.N())     # 전체 토큰의 수를 알려줌

# 핵심
print(freq.most_common(10))         # 최빈값 n 개 출력
print(len(freq.most_common()))

counts = [c for _, c in freq.most_common(5)]
names = [w for w, _ in freq.most_common(5)]
# plt.subplot(2, 2, 1)
# plt.plot(range(5), d1, 'r')
# #plt.figure()
# plt.subplot(2, 3, 4)
# plt.plot(range(5), d2, 'g')
# plt.show()
# plt.bar(range(5), counts)
# plt.xticks(range(5), names)
plt.bar(names, counts)
plt.show()