반응형

Yes Cyber solution is best.

For beginners

  1. Read file in Read mode.
  2. Iterate lines by readlines() or readline()
  3. Use split(",") method to split line by '
  4. Use float to convert string value to float. OR We can use eval() also.
  5. Use list append() method to append tuple to list.
  6. Use try except to prevent code from break.
My text file is:

-34.968398,-6.487265
-34.969448,-6.488250
-34.967364,-6.492370
-34.965735,-6.582322


Code:

p = "/home/vivek/Desktop/test.txt"
result = []
with open(p, "rb") as fp:
    for i in fp.readlines():
        tmp = i.split(",")
        try:
            result.append((float(tmp[0]), float(tmp[1])))
            #result.append((eval(tmp[0]), eval(tmp[1])))
        except:pass

print result


Output:

$ python test.py 
[(-34.968398, -6.487265), (-34.969448, -6.48825), (-34.967364, -6.49237), (-34.965735, -6.582322)]

Read file as a list of tuples, 파일읽어서 튜플 만들기

 

 

반응형
반응형

style cloud 설정

 

> pip install stylecloud

 

 

- file_path: 입력할 데이터를 텍스트 문서로 지정합니다.

- text: 입력할 데이터를 딕셔너리 자료형으로 지정합니다.

- font_path: 워드클라우드를 그릴 path를 지정합니다.

- size: 사이즈를 지정, (1024, 512)과 같은 형식으로 입력합니다.

- background_color: 배경색을 지정한다. 색이름을 입력하면 된다. ( 예) white )

- icon_name: 어떤 모양으로 그릴 지 입력합니다. fab fa-twitter(트워터 모양), fas fa-dog(강아지), fas fa-flag(깃발), fas fa-fish(물고기) 등이 있다. 띄어쓰기 앞은 폰트를 의미하고, 뒤에는 모양을 의미한다. 그릴 수 있는 모양은 가지수가 좀 많은데, stylecolud패키지가 설치된 폴더에서 static폴더 밑에 fontawesome.min.css파일을 확인하면 알 수 있다.

- font_path: 폰트를 지정한다.

- output_name: 결과를 파일로 저장한다.

 

Generate Modern Stylish Wordcloud : towardsdatascience.com/generate-modern-stylish-wordcloud-with-stylecloud-9cbb059696d2

 

Generate Modern Stylish Wordcloud with stylecloud

But deep down, all of us have always wished for modern-stylish-beautiful wordclouds. That wish has become true with this new python…

towardsdatascience.com

파이썬 wordcloud를 사용한 한글 명사 시각화 :  liveyourit.tistory.com/58

 

파이썬 wordcloud를 사용한 한글 명사 시각화

파이썬 wordcloud는 중요한 단어나 키워드를 시각화해서 보여주는 시각화 도구이다. wordcloud 자체적으로 빈도수를 계산하는 기능이 있다고 하지만 아무래도 한글의 특성이 있다보니, 나는 한글 명

liveyourit.tistory.com

 

#워드 클라우드, 파이썬에서 이쁘게 그리는 방법은 tariat.tistory.com/854?category=678887

 

워드 클라우드, 파이썬에서 이쁘게 그리는 방법은?!

빅데이터가 많은 사람들에게 관심을 받기 시작할 때 많이 볼 수 있었던 것 중에 하나로 워드 클라우드가 있다. 워드 클라우드는 단어별 빈도수를 기준으로 한 단순한 시각화에 불과하지만, 그림

tariat.tistory.com

 

반응형
반응형

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
반응형
반응형

Word Tokenization 단어 토큰화

 

자연어 처리에서 크롤링 등으로 얻어낸 코퍼스 데이터가 필요에 맞게 전처리되지 않은 상태라면, 해당 데이터를 사용하고자하는 용도에 맞게 토큰화(tokenization) & 정제(cleaning) & 정규화(normalization)하는 일을 하게 됩니다. 이번 챕터에서는 그 중에서도 토큰화에 대해서 배우도록 합니다.

주어진 코퍼스(corpus)에서 토큰(token)이라 불리는 단위로 나누는 작업을 토큰화(tokenization)라고 부릅니다. 토큰의 단위가 상황에 따라 다르지만, 보통 의미있는 단위로 토큰을 정의합니다.

이 챕터에서는 토큰화에 대한 발생할 수 있는 여러가지 상황에 대해서 언급하여 토큰화에 대한 개념을 이해합니다. 뒤에서 파이썬과 NLTK 패키지, KoNLPY를 통해 실습을 진행하며 직접 토큰화를 수행해보겠습니다.

 

 


## word_tokenize는 Don't를 Do와 n't로 분리하였으며, 
## 반면 Jone's는 Jone과 's로 분리한 것을 확인할 수 있습니다.
>from nltk.tokenize import word_tokenize  
>print(word_tokenize("Don't be fooled by the dark sounding name, Mr. Jone's Orphanage is as cheery as cheery goes for a pastry shop."))  
['Do', "n't", 'be', 'fooled', 'by', 'the', 'dark', 'sounding', 'name', ',', 'Mr.', 'Jone', "'s", 'Orphanage', 'is', 'as', 'cheery', 'as', 'cheery', 'goes', 'for', 'a', 'pastry', 'shop', '.']  


## WordPunctTokenizer는 구두점을 별도로 분류하는 특징을 갖고 있기때문에, 앞서 확인했던
## word_tokenize와는 달리 Don't를 Don과 '와 t로 분리하였으며, 
## 이와 마찬가지로 Jone's를 Jone과 '와 s로 분리한 것을 확인할 수 있습니다.
>from nltk.tokenize import WordPunctTokenizer  
>print(WordPunctTokenizer().tokenize("Don't be fooled by the dark sounding name, Mr. Jone's Orphanage is as cheery as cheery goes for a pastry shop."))
['Don', "'", 't', 'be', 'fooled', 'by', 'the', 'dark', 'sounding', 'name', ',', 'Mr', '.', 'Jone', "'", 's', 'Orphanage', 'is', 'as', 'cheery', 'as', 'cheery', 'goes', 'for', 'a', 'pastry', 'shop', '.']  


## 케라스 또한 토큰화 도구로서 text_to_word_sequence를 지원합니다. 이번에는 케라스로 토큰화를 수행해봅시다.
## 케라스의 text_to_word_sequence는 기본적으로 모든 알파벳을 소문자로 바꾸면서 온점이나 
## 컴마, 느낌표 등의 구두점을 제거합니다. 하지만 don't나 jone's와 같은 경우 아포스트로피는 보존하는 것을 볼 수 있습니다.
>from tensorflow.keras.preprocessing.text import text_to_word_sequence
>print(text_to_word_sequence("Don't be fooled by the dark sounding name, Mr. Jone's Orphanage is as cheery as cheery goes for a pastry shop."))
["don't", 'be', 'fooled', 'by', 'the', 'dark', 'sounding', 'name', 'mr', "jone's", 'orphanage', 'is', 'as', 'cheery', 'as', 'cheery', 'goes', 'for', 'a', 'pastry', 'shop']


## 표준으로 쓰이고 있는 토큰화 방법 중 하나인 Penn Treebank Tokenization의 규칙에 대해서 소개하고, 토큰화의 결과를 보도록 하겠습니다.
## 규칙 1. 하이푼으로 구성된 단어는 하나로 유지한다.
## 규칙 2. doesn't와 같이 아포스트로피로 '접어'가 함께하는 단어는 분리해준다. 
>from nltk.tokenize import TreebankWordTokenizer
>tokenizer=TreebankWordTokenizer()
>text="Starting a home-based restaurant may be an ideal. it doesn't have a food chain or restaurant of their own."
>print(tokenizer.tokenize(text))
['Starting', 'a', 'home-based', 'restaurant', 'may', 'be', 'an', 'ideal.', 'it', 'does', "n't", 'have', 'a', 'food', 'chain', 'or', 'restaurant', 'of', 'their', 'own', '.']
반응형
반응형

online python compiler : www.onlinegdb.com/online_python_compiler

 

Online Python Compiler - online editor

OnlineGDB is online IDE with python compiler. Quick and easy way to compile python program online. It supports python3.

www.onlinegdb.com

 

python 공식홈페이지 온라인 쉘 : www.python.org/shell/

 

Welcome to Python.org

The official home of the Python Programming Language

www.python.org

반응형
반응형

딥 러닝을 이용한 자연어 처리 입문

wikidocs.net/book/2155

 

위키독스

온라인 책을 제작 공유하는 플랫폼 서비스

wikidocs.net

 

반응형
반응형

[Python] argparse 사용법 (파이썬 인자값 추가하기)

 

두개의 인자 path, savefilename 을 받음.

(env) C:\__STT>python transcribe_async_gcs.py gs://cloud-samples-tests/speech/vr.flac 12345
Waiting for operation to complete...
Transcript: it's okay so what am I doing here why am I here at GDC talking about VR video it's because I believe my favorite games I love games I believe in games my favorite games are the ones that are all about the stories I love narrative game design I love narrative-based games and I think that when it comes to telling stories in VR bring together capturing the world with narrative based games and narrative based game design is going to unlock some of the killer apps and killer stories of the medium
Confidence: 0.9580045938491821
Transcript: so I'm really here looking for people who are interested in telling us or two stories that are planning projects around telling those types of stories and I would love to talk to you so if it sounds like your project if you're looking at blending VR video and interactivity to tell a story I want to talk to you I want to help you so if this sounds like you please get in touch with you can't find me I'll be here all week I have pink hair I work for Google and I would love to talk with you further about VR video interactivity and storytelling
Confidence: 0.949270486831665
completed
if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument("path", help="File or GCS path for audio file to be recognized")  
    parser.add_argument("savefilename", help="Save fileName ")   
    args = parser.parse_args()

    response = transcribe_gcs(args.path)
    
    with open("stt_"+args.savefilename+".txt", "w") as script:
        for result in response.results:
            script.write(u'Transcript: {}'.format(result.alternatives[0].transcript)+"\n")
            script.write(u'Confidence: {}'.format(result.alternatives[0].confidence)+"\n")
            script.write(u'Channel Tag: {}'.format(result.alternatives[0].channel_tag)+"\n")

docs.python.org/ko/3/library/argparse.html

 

argparse — 명령행 옵션, 인자와 부속 명령을 위한 파서 — Python 3.9.0 문서

argparse — 명령행 옵션, 인자와 부속 명령을 위한 파서 소스 코드: Lib/argparse.py argparse 모듈은 사용자 친화적인 명령행 인터페이스를 쉽게 작성하도록 합니다. 프로그램이 필요한 인자를 정의하면

docs.python.org

 

docs.python.org/ko/3/howto/argparse.html

 

Argparse 자습서 — Python 3.9.0 문서

Argparse 자습서 저자 Tshepang Lekhonkhobe 이 자습서는 파이썬 표준 라이브러리에서 권장하는 명령행 파싱 모듈인 argparse 에 대한 소개입니다. 참고 같은 작업을 수행하는 다른 두 모듈이 있습니다, geto

docs.python.org

 

반응형

+ Recent posts