반응형

sorted, 문자열 길이로 정렬, 한글 정렬

the_list.sort() # sorts normally by alphabetical order
the_list.sort(key=len, reverse=True) # sorts by descending length


the_list.sort(key=lambda item: (-len(item), item))




#########################################


n = ['aaa', 'bbb', 'ccc', 'dddd', 'dddl', 'yyyyy']

for i in reversed(sorted(n, key=len)):
       print i
       
       
for i in sorted(n, key=len, reverse=True):
        print i

 

-Sort your list by alpha order, then by length.

See the following exmple:

>>> coursesList = ["chemistry","physics","mathematics","art"]
>>> sorted(coursesList,key=len)
['art', 'physics', 'chemistry', 'mathematics']
>>> coursesList.append("mopsosa")
>>> sorted(coursesList,key=len)
['art', 'physics', 'mopsosa', 'chemistry', 'mathematics']
>>> coursesList.sort()
>>> sorted(coursesList,key=len)
['art', 'mopsosa', 'physics', 'chemistry', 'mathematics']
반응형
반응형

큰 txt파일을 읽으면 메모리 문제 발생하기때문에 분할해서 단어장 처리. 

 

import os
import sys
import konlpy
import pandas as pd
import numpy as np
os.environ['JAVA_OPTS'] = 'Xmx4096M'

import itertools

import mr #local module

file_name = "test_export_mentions_2020-11-17_title.txt"
#file_name = "test_export_mentions_2020-11-17_title_utf8.txt"  #test
file_out  = "outputfile"
lines_tot = mr.file_len(file_name)
filesize  = mr.getfilesize(file_name) * 1000
print("파일명 : ", file_name)
print("줄 개수 : ", lines_tot)
print("파일사이즈 : ", filesize)

f = open(file_name,'r', encoding='utf-8')
numbits  = 1000000
loop_num = round(os.stat(file_name).st_size/numbits+1)+1

print(os.stat(file_name).st_size/numbits+1)
print(loop_num)

for i in range(0, loop_num):
    o = open('./input/'+file_out+str(i)+'.txt','w', encoding='utf-8')
    segment = f.readlines(numbits)
    for c in range(0,len(segment)):
        o.write(segment[c]+"\n")
    o.close()


 
import itertools

def f_append(text):
    sign = 'N'
    #기존 파일의 단어를 가져와서 신규 단어가 있는지 확인
    with open('./replace_word.txt','r',encoding='utf-8') as f:
        list_word = f.read().strip().split('\n')
        for line in list_word:
            if line == text:
                sign = 'Exist'
                #print('Exist')
        '''
        list_word = f.read()
        if list_word.find(text) >=0:
            sign = 'N'
            print('Exist')
        '''
    if sign == 'N':
        #기존 파일에 단어추가
        with open('./replace_word.txt', 'a', encoding='utf-8') as myfile:
            myfile.write(text)
            myfile.write('\n')
            sign = 'Yes'

    return sign

def f_list():
    #단어파일을 list로 리턴
    with open('./replace_word.txt','r',encoding='utf-8') as f:
        list_word = f.read().strip().split('\n')
    return list_word

def f_del(text):
    #입력받은 단어를 삭제
    sign = 'N'
    matrix = []
    with open('./replace_word.txt','r',encoding='utf-8') as f:
        dic = f.read().strip().split('\n')

    for word in dic:
        if word != text:
            matrix.append(word)
        else:
            sign = 'Del';
    print(sign)
    print(dic)

    if sign == 'Del':
        with open('./replace_word.txt', 'w', encoding='utf-8') as myfile:
            #myfile.write(matrix)
            for line2 in matrix:
                print(line2)
                myfile.write(line2)
                myfile.write('\n')
            sign = 'Y'

    return sign
반응형
반응형

komorandocs.readthedocs.io/ko/latest/pykomoran/installation.html

 

PyKomoran 설치하기 — KOMORAN documentation

이 문서에서는 Python에서 KOMORAN을 사용하기 위해 PyKOMORAN을 설치하는 방법을 살펴보도록 하겠습니다. 주석 PyKOMORAN은 KOMORAN을 Python에서 사용할 수 있도록 하는 프로젝트입니다. 이는 KOMORAN을 Python

komorandocs.readthedocs.io

konlpy-ko.readthedocs.io/ko/latest/api/konlpy.tag/#okt-class

 

tag Package — KoNLPy 0.5.2 documentation

매개 변수: jvmpath -- The path of the JVM passed to init_jvm(). userdic -- The path to the user dictionary. This enables the user to enter custom tokens or phrases, that are mandatorily assigned to tagged as a particular POS. Each line of the dictionar

konlpy-ko.readthedocs.io

konlpy-ko.readthedocs.io/ko/latest/api/konlpy.tag/#module-konlpy.tag._komoran

 

tag Package — KoNLPy 0.5.2 documentation

매개 변수: jvmpath -- The path of the JVM passed to init_jvm(). userdic -- The path to the user dictionary. This enables the user to enter custom tokens or phrases, that are mandatorily assigned to tagged as a particular POS. Each line of the dictionar

konlpy-ko.readthedocs.io

> pip install PyKomoran

> python

>>> from PyKomoran import *
>>> komoran = Komoran(DEFAULT_MODEL['FULL'])
>>>
>>> from konlpy.tag import Okt
>>> okt = Okt()

>>> okt.nouns(u'오픈소스에 관심 많은 ')
['오픈소스', '관심']

>>> komoran.nouns(u'오픈소스에 관심 많은 ')
['오픈', '소스', '관심']
>>>

 

 

 

반응형
반응형

 Customized Konlpy 사용하기

 

okt 에 dict 추가하기

https://inspiringpeople.github.io/data%20analysis/ckonlpy/

 

Customized Konlpy 사용하기

Text Mining 데이터 분석은 다른 데이터 종류 분석보다 손이 많이 가고 데이터를 더 많이 들여다보아야 한다.특히, 한국어 Text Mining은 같은 의미 단어라도 뒤에 붙는 조사/어미에 따라 변형될 수 있

inspiringpeople.github.io

Ckonlpy로 전처리하고 형태소 분석하기

전처리 단에서는 단어 추가, 치환, 필터, 복합명사 변환 작업 등을 하면서 data cleansing 작업을 한다.
Ckonlpy에서는 add_dictionary 함수와 Postprocessor 모듈을 통해서 이와 같은 작업을 할 수 있다.

  • 단어 추가 : domain specific한 단어 추가 (ex. 아이오아이, 트와이스 ..)
  • 단어 치환 : 오타 관련 cleansing 작업 (ex. 잇다 -> 있다 ..)
  • 단어 선택 : 선택한 단어/품사만 추출
  • 단어 필터 : 너무 general 데이터 분석에 도움이 안되는 단어들 삭제 (ex. 나, 너..)
  • 단어 결합 : n-gram 이상의 단어를 한 단어로 결합

단어 추가 (add_dictionary)

기존 트위터 분석기 사전에 존재하지 않는 단어를 추가할 때 사용한다.
자신이 분석하는 domain specific 단어를 추가할 때 유용하다.

  • add_dictionary 함수 사용 : 단어 또는 단어 리스트 단위로 등록
  • 사전 파일 등록 : 파일 단위로 단어 뭉치 등록
    위치 : customized_konlpy/ckonlpy/data/twitter (자신이 등록하는 파일의 품사에 따라 등록)

주의사항 !!!
파일 단위로 단어를 등록하는 경우에는 등록한 이후 pip install customized_konlpy를 다시 실행시켜줘야 반영이 된다.

반응형
반응형

konlpy에서 다음과 같은 에러가 나옵니다. TypeError: No matching overloads found for kr.lucypark.okt.OktInterface.tokenize(list,java.lang.Boolean,java.lang.Boolean), options are: public java.util.List kr.lucypark.okt.OktInterface.tokenize(java.lang.String,java.lang.Boolean,java.lang.Boolean)

`from konlpy.tag import Okt
from konlpy import jvm
from konlpy.corpus import kolaw
import nltk
from collections import Counter

twitter=Okt()

file = open("d:/study/test.txt", 'r')
data = file.readlines()
file.close()
data

news_word=twitter.nouns(data)`

 

news_word=twitter.nouns(data)

이 부분에서 자꾸 에러가 나는데요.

 

현재 data는 test.txt의 각 줄을 원소로 하는 문자열 배열입니다.

Konlpy의 함수는 배열을 인자로 받지 않고, 보통 문자열을 받습니다.
이 경우에는 data를 for문을 돌면서 사용하셔야 합니다.

for data in line:
   news_word = twitter.nouns(line)
   
   

이렇게 얻은 news_word를 적절히 활용하시면 됩니다.

반응형
반응형
fontpath = "C:/Windows/Fonts/NanumBarunGothic.ttf"

[python] SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape 에러 해결법

 

\를  /로 변경해서 적용하니까 에러 안남. 

반응형
반응형

seaborn: statistical data visualization

 

seaborn.pydata.org/examples/index.html

 

Example gallery — seaborn 0.11.0 documentation

 

seaborn.pydata.org

 

반응형
반응형

gspread를 이용하여 Python에서 구글 시트 연동하기

public-google-sheets-parser 

yurimkoo.github.io/python/2019/07/20/link-with-googlesheets-for-Python.html

 

유림's Blog

베짱이가 되고 싶은 개미의 기술 블로그

yurimkoo.github.io

 

googlesheets를 이용하여 R에서 구글 시트 연동하기

yurimkoo.github.io/r/2019/07/20/link-with-googlesheets-for-R.html

 

유림's Blog

베짱이가 되고 싶은 개미의 기술 블로그

yurimkoo.github.io

 

반응형

+ Recent posts