반응형

[python] 초보자를 위한 파이썬 300제

 

파이썬 기초 문법을 배웠다고 해서 누구나 프로그래밍에 익숙해지는 것은 아닙니다. 프로그래밍에 익숙해지기까지 많은 문제를 풀어보고 익숙해지는 것이 필요합니다. 파이썬 300제는 파이썬 기초 문법과 관련된 문제들을 제공합니다. 파이썬 300제를 통해 지금까지 배운 기초 문법을 익혀보세요. 문제를 풀다가 막히는 부분은 각 문제 페이지 하단에 있는 유튜브 동영상을 참고하세요.

https://www.youtube.com/watch?v=SiK4iYt_7-s 

https://wikidocs.net/book/922

 

초보자를 위한 파이썬 300제

파이썬 기초 문법을 배웠다고 해서 누구나 프로그래밍에 익숙해지는 것은 아닙니다. 프로그래밍에 익숙해지기까지 많은 문제를 풀어보고 익숙해지는 것이 필요합니다. 파이썬 300제 ...

wikidocs.net

 

반응형
반응형

dictionary 를 json 으로 변환

 

https://docs.python.org/2/library/json.html

 

18.2. json — JSON encoder and decoder — Python 2.7.18 documentation

18.2. json — JSON encoder and decoder JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 4627) and by ECMA-404, is a lightweight data interchange format inspired by JavaScript object literal syntax (although it is not a strict

docs.python.org

import json

dict1 = { 'name' : 'song', 'age' : 10 }

print "dict1 = %s" % dict1
print "dict1 type = %s" % type(dict1)
print "================"

# CONVERT dictionary to json using json.dump
json_val = json.dumps(dict1)


print "json_val = %s" % json_val
print "json_val type = %s" % type(json_val)
반응형
반응형

   
## 시간 표시  ##################################### 
import time
import datetime
now = datetime.datetime.now()

timeserise = time.time()
timeserise = str(int(timeserise))
print(timeserise)
print(now)
#################################################  

#작업하는 경로(위치)가 어디인지 확인
print(os.getcwd())

prePath = "./Project/DataCrawring/"


# CSV 파일로 저장
def dfToCsv(movie_df, num):
    try:
        # 파일이 존재하면 누적저장 mode='a', header=False
        if not os.path.exists(prePath  +'input/movie_data'+str(num) +'.csv'): 
            #movie_df.to_csv((prePath  +'input/movie_data'+str(num) +'.csv'),   header=False, line_terminator=False, encoding='utf-8-sig')        
            movie_df.to_csv((prePath  +'input/movie_data'+str(num) +'.csv'),   index=False, mode='w', header=True, line_terminator=False, encoding='utf-8-sig')
            print("First Save Success~~~ ")        
        else:
            movie_df.to_csv((prePath  +'input/movie_data'+str(num) +'.csv'),   index=False, mode='a', header=False, line_terminator=False, encoding='utf-8-sig')
            print("Add Save Success~~~ ")        
    except:
        print("Error - dfToCsv.....")

pandas 결과값을 csv 파일 형식으로 누적해서 저장하기: to_csv

 

to_csv Append Mode 사용하기

import pandas as pd
import os

# 샘플 데이터 생성
soda = {'상품명': ['콜라', '사이다'], '가격': [2700, 2000]}
df = pd.DataFrame(soda)

# .to_csv 
# 최초 생성 이후 mode는 append
if not os.path.exists('output.csv'):
    df.to_csv('output.csv', index=False, mode='w', encoding='utf-8-sig')
else:
    df.to_csv('output.csv', index=False, mode='a', encoding='utf-8-sig', header=False)

encoding='utf-8' 사용시 한글깨짐 현상이 발생하여, 'utf-8-sig'를 사용하였습니다. utf-8-sig에 관한 더 자세한 내용은 https://stackoverflow.com/questions/25788037/pandas-df-to-csvfile-csv-encode-utf-8-still-gives-trash-characters-for-min를 참고해주세요.

 

 

 

반응형
반응형

웹 크롤링 준비 - Beautifulsoup4, reqeusts 

 

conda install beautifulesoup4

conda install requests

conda install selenium

conda install urllib3

conda install openpyxl

 

 

 

반응형
반응형

이런 에러시  " Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found "

 

1. CUDA 최신 버전 다운로드

https://developer.nvidia.com/cuda-toolkit-archive

 

 

2. Path 추가

 

내컴퓨터 - 우클릭 속성 - 고급 시스템 설정 - 고급 - 환경 변수

 

시스템 변수에 Path 편집

아래 두줄이 포함되어 있어야 합니다.

C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.4\bin

C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.4\libnvvp

 

* 설치하니까 자동으로 생성이 된다. 

 

3. 텐서플로우 재설치

터미널에서 텐서플로우를 다시 인스톨해 주세요

pip install tensorflow

 

 

 

4.기타

이외에도 duDNN을 설치 하라고 하는데 제 케이스에는 설치 없이 되었습니다.

위에서도 안된다면 아래 사이트에서 다운 받아 설치해 주세요.

 

https://developer.nvidia.com/rdp/cudnn-archive

 

cuDNN Archive

NVIDIA cuDNN is a GPU-accelerated library of primitives for deep neural networks.

 

 

# 참조 : https://sheepone.tistory.com/126

 

 

 

반응형
반응형

conda update

 


Anaconda Prompt 에 들어오면 conda 패키지 관리자를 사용할 수 있게 됩니다.


> conda activate main

1.우선 conda 자체를 업그레이드 해줍니다.

> conda update -n base conda

2.다음으로 설치된 파이썬 패키지를 모두 최신 버전으로 업데이트 해줍니다.

>conda update -all 

3. tensorflow 를 설치합니다

>pip install tensorflow 

4.keras도 설치해줍니다

>pip install keras
반응형
반응형

[python] mpld3를 이용해서 python의 그림을 웹에 올려보자.https://frhyme.github.io/python-libs/plt_mpld3/#matplotlibpyplot%EB%A1%9C-%EA%B7%B8%EB%A6%B0-%EA%B7%B8%EB%A6%BC%EC%9D%84-%ED%8E%B8%ED%95%98%EA%B2%8C-html%EB%A1%9C-%EB%B0%94%EA%BE%B8%EC%9E%90

 

mpld3를 이용해서 python의 그림을 웹에 올려보자.

matplotlib.pyplot로 그린 그림을 편하게 html로 바꾸자.

frhyme.github.io

 

matplotlib.pyplot로 그린 그림을 편하게 html로 바꾸자.Permalink

  • 파이썬으로 코딩하는 사람들은 시각화할때 대부분 matplotlib를 사용할 것이라고 생각합니다. 특히 matplotlib는 jupyter notebook과 붙으면 매우 굉-장해집니다. 그림을 바로 그리고 고치고, 다시 그리고 괜찮으면 저장, 하는 등의 작업을 수행하게 되죠.
  • 아무튼, 그냥 개인이 저장해서 처리한다면 아무 문제가 없지만, 이걸 웹에 뿌려주고 싶을 때는 이게 생각처럼 되지 않습니다. 그냥 그림으로 만들어서 전달해도 되지만, 그럴 경우에는 화면의 비율등에 따라서 깨질 수 있고, 이는 글자크기, 간격 등에 모두 영향을 미치게 되니까 아주 엉망인 그림이 만들어질 가능성이 높습니다.
    • 물론 svg파일로 만들어서 전달하는 것도 방법입니다만, 이 경우에도 어느 정도의 문제가 발생할 수는 있습니다.
  • 가장 좋은 선택지는, 웹상의 요소로 변환하는 것이 될것이고, 그 방법중 하나로 mpld3와 같은 라이브러리를 사용해서 처리할 수 있습니다.

what is mpld3?Permalink

The mpld3 project brings together Matplotlib, the popular Python-based graphing library, and D3js, the popular JavaScript library for creating interactive data visualizations for the web. The result is a simple API for exporting your matplotlib graphics to HTML code which can be used within the browser, within standard web pages, blogs, or tools such as the IPython notebook.

  • 공식 홈페이지에서 가져왔습니다. 간단히 정리하면, mpld3는 매트플롯립과 d3js를 사용해서 웹의 인터랙티브 데이터 시각화 를 가능하도록 만드는 것이 목적이라고 하네요. 간단하게, matpllitb의 그래픽을 html코드로(코드를 뜯어보면, 사실 거의 d3js 코드입니다만), 변환해줍니다. 이걸 가지고, 차트 같은 것을 좀 더 편하게 변환할 수 있겠죠.

do it.Permalink

  • 다음처럼 figure를 만들고, 그 figure를 html로 내뱉으면 됩니다.
    • html을 저장하든(save_html), 결과를 스트링으로 가져오든 뭘하든 간에 맥에서는 잘 작동하지 않습니다.
!pip install mpld3

import json
import mpld3
import matplotlib.pyplot as plt

f = plt.figure()
plt.plot([1,2,3], [4,5,6])

print(mpld3.fig_to_html(f, figid='THIS_IS_FIGID'))

  • 아래처럼 html 페이지로 만들어집니다.
<style>

</style>

<div id="THIS_IS_FIGID"></div>
<script>
function mpld3_load_lib(url, callback){
  var s = document.createElement('script');
  s.src = url;
  s.async = true;
  s.onreadystatechange = s.onload = callback;
  s.onerror = function(){console.warn("failed to load library " + url);};
  document.getElementsByTagName("head")[0].appendChild(s);
}

if(typeof(mpld3) !== "undefined" && mpld3._mpld3IsLoaded){
   // already loaded: just create the figure
   !function(mpld3){
       
       mpld3.draw_figure("THIS_IS_FIGID", {"width": 576.0, "height": 396.0, "axes": [{"bbox": [0.125, 0.125, 0.775, 0.755], "xlim": [0.9, 3.1], "ylim": [3.9, 6.1], "xdomain": [0.9, 3.1], "ydomain": [3.9, 6.1], "xscale": "linear", "yscale": "linear", "axes": [{"position": "bottom", "nticks": 11, "tickvalues": null, "tickformat": null, "scale": "linear", "fontsize": 10.0, "grid": {"gridOn": true, "color": "#FFFFFF", "dasharray": "none", "alpha": 1.0}, "visible": true}, {"position": "left", "nticks": 11, "tickvalues": null, "tickformat": null, "scale": "linear", "fontsize": 10.0, "grid": {"gridOn": true, "color": "#FFFFFF", "dasharray": "none", "alpha": 1.0}, "visible": true}], "axesbg": "#EAEAF2", "axesbgalpha": null, "zoomable": true, "id": "el149140466966796328", "lines": [{"data": "data01", "xindex": 0, "yindex": 1, "coordinates": "data", "id": "el149140466967383568", "color": "#4C72B0", "linewidth": 1.75, "dasharray": "none", "alpha": 1, "zorder": 2, "drawstyle": "default"}], "paths": [], "markers": [], "texts": [], "collections": [], "images": [], "sharex": [], "sharey": []}], "data": {"data01": [[1.0, 4.0], [2.0, 5.0], [3.0, 6.0]]}, "id": "el149140466979442984", "plugins": [{"type": "reset"}, {"type": "zoom", "button": true, "enabled": false}, {"type": "boxzoom", "button": true, "enabled": false}]});
   }(mpld3);
}else if(typeof define === "function" && define.amd){
   // require.js is available: use it to load d3/mpld3
   require.config({paths: {d3: "https://mpld3.github.io/js/d3.v3.min"}});
   require(["d3"], function(d3){
      window.d3 = d3;
      mpld3_load_lib("https://mpld3.github.io/js/mpld3.v0.3.js", function(){
         
         mpld3.draw_figure("THIS_IS_FIGID", {"width": 576.0, "height": 396.0, "axes": [{"bbox": [0.125, 0.125, 0.775, 0.755], "xlim": [0.9, 3.1], "ylim": [3.9, 6.1], "xdomain": [0.9, 3.1], "ydomain": [3.9, 6.1], "xscale": "linear", "yscale": "linear", "axes": [{"position": "bottom", "nticks": 11, "tickvalues": null, "tickformat": null, "scale": "linear", "fontsize": 10.0, "grid": {"gridOn": true, "color": "#FFFFFF", "dasharray": "none", "alpha": 1.0}, "visible": true}, {"position": "left", "nticks": 11, "tickvalues": null, "tickformat": null, "scale": "linear", "fontsize": 10.0, "grid": {"gridOn": true, "color": "#FFFFFF", "dasharray": "none", "alpha": 1.0}, "visible": true}], "axesbg": "#EAEAF2", "axesbgalpha": null, "zoomable": true, "id": "el149140466966796328", "lines": [{"data": "data01", "xindex": 0, "yindex": 1, "coordinates": "data", "id": "el149140466967383568", "color": "#4C72B0", "linewidth": 1.75, "dasharray": "none", "alpha": 1, "zorder": 2, "drawstyle": "default"}], "paths": [], "markers": [], "texts": [], "collections": [], "images": [], "sharex": [], "sharey": []}], "data": {"data01": [[1.0, 4.0], [2.0, 5.0], [3.0, 6.0]]}, "id": "el149140466979442984", "plugins": [{"type": "reset"}, {"type": "zoom", "button": true, "enabled": false}, {"type": "boxzoom", "button": true, "enabled": false}]});
      });
    });
}else{
    // require.js not available: dynamically load d3 & mpld3
    mpld3_load_lib("https://mpld3.github.io/js/d3.v3.min.js", function(){
         mpld3_load_lib("https://mpld3.github.io/js/mpld3.v0.3.js", function(){
                 
                 mpld3.draw_figure("THIS_IS_FIGID", {"width": 576.0, "height": 396.0, "axes": [{"bbox": [0.125, 0.125, 0.775, 0.755], "xlim": [0.9, 3.1], "ylim": [3.9, 6.1], "xdomain": [0.9, 3.1], "ydomain": [3.9, 6.1], "xscale": "linear", "yscale": "linear", "axes": [{"position": "bottom", "nticks": 11, "tickvalues": null, "tickformat": null, "scale": "linear", "fontsize": 10.0, "grid": {"gridOn": true, "color": "#FFFFFF", "dasharray": "none", "alpha": 1.0}, "visible": true}, {"position": "left", "nticks": 11, "tickvalues": null, "tickformat": null, "scale": "linear", "fontsize": 10.0, "grid": {"gridOn": true, "color": "#FFFFFF", "dasharray": "none", "alpha": 1.0}, "visible": true}], "axesbg": "#EAEAF2", "axesbgalpha": null, "zoomable": true, "id": "el149140466966796328", "lines": [{"data": "data01", "xindex": 0, "yindex": 1, "coordinates": "data", "id": "el149140466967383568", "color": "#4C72B0", "linewidth": 1.75, "dasharray": "none", "alpha": 1, "zorder": 2, "drawstyle": "default"}], "paths": [], "markers": [], "texts": [], "collections": [], "images": [], "sharex": [], "sharey": []}], "data": {"data01": [[1.0, 4.0], [2.0, 5.0], [3.0, 6.0]]}, "id": "el149140466979442984", "plugins": [{"type": "reset"}, {"type": "zoom", "button": true, "enabled": false}, {"type": "boxzoom", "button": true, "enabled": false}]});
            })
         });
}
</script>

wrap-upPermalink

  • mpld3 example gallery에 들어가면 그 외에도 다양한 예제들이 있습니다만, 이걸 다 정확하게 이해하려면 d3js를 잘 알아야 하는 것 같습니다.
  • 또한 아쉽게도 networkx를 통해서 그린 그림에 대해서는 잘 만들어주지 않습니다. 결국 이건 다른 라이브러리를 사용해서 변환하는 쪽으로 생각해야 할 것 같아요. 정 안되면, 그냥 svg로 만들어서 뿌려주는 것이 가장 효과적인 것 같습니다.

 

 

반응형
반응형

[python] How to write to an HTML file in Python

https://www.kite.com/python/answers/how-to-write-to-an-html-file-in-python

 

Kite - Free AI Coding Assistant and Code Auto-Complete Plugin

Code faster with Kite’s AI-powered autocomplete plugin for over 16 programming languages and 16 IDEs, featuring Multi-Line Completions. Works 100% locally.

www.kite.com

USE open() AND file.write() TO WRITE TO AN HTML FILE

Use open(file, mode) with mode as "w" to create a new HTML file file or write to an existing one. Use file.write(data) to write data to the file. Use file.close() to close the file after writing.

text = '''
<html>
    <body>
        <h1>Heading</h1>
    </body>
</html>
'''
file = open("sample.html","w")
file.write(text)
file.close()
SAMPLE.HTML
<html>
    <body>
        <h1>Heading</h1>
    </body>
</html>
반응형

+ Recent posts