# 자주 쓸 것 같은 Third-party packages 메모



# 강의에서 추천


  • IPython - A better interactive Python interpreter
  • requests - Provides easy to use methods to make web requests. Useful for accessing web APIs.
  • Flask - a lightweight framework for making web applications and APIs.
  • Django - A more featureful framework for making web applications. Django is particularly good for designing complex, content heavy, web applications.
  • Beautiful Soup - Used to parse HTML and extract information from it. Great for web scraping.
  • pytest - extends Python's builtin assertions and unittest module.
  • PyYAML - For reading and writing YAML files.
  • NumPy - The fundamental package for scientific computing with Python. It contains among other things a powerful N-dimensional array object and useful linear algebra capabilities.
  • pandas - A library containing high-performance, data structures and data analysis tools. In particular, pandas provides dataframes!
  • matplotlib - a 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments.
  • ggplot - Another 2D plotting library, based on R's ggplot2 library.
  • Pillow - The Python Imaging Library adds image processing capabilities to your Python interpreter.
  • pyglet - A cross-platform application framework intended for game development.
  • Pygame - A set of Python modules designed for writing games.
  • pytz - World Timezone Definitions for Python




# Third-party packages 버전 고정법

- 하나의 서드파티 패키지도 여러개의 버전으로 나뉘고 이로인해 문제가 생기는 경우 고정해서 쓴다.

- requirements.txt 파일을 만들어서 고정할 패키지와 버전의 list를 나열한다.

beautifulsoup4==4.5.1
bs4==0.0.1
pytz==2016.7
requests==2.11.1

- 이것을 python에 반영한다.

$ pip3 install -r requirements.txt



Reference:

- https://classroom.udacity.com/courses/ud1110

# 자주 쓸 것 같은 Python Standard libraries 메모



# Python Standard library: https://docs.python.org/3/library/



# 강의에서 추천


  • csv: very convenient for reading and writing csv files
  • collections: useful extensions of the usual data types including OrderedDictdefaultdict and namedtuple
  • random: generates pseudo-random numbers, shuffles sequences randomly and chooses random items
  • string: more functions on strings. This module also contains useful collections of letters like string.digits (a string containing all characters with are valid digits).
  • re: pattern-matching in strings via regular expressions
  • math: some standard mathematical functions
  • os: interacting with operating systems
  • os.path: submodule of os for manipulating path names
  • sys: work directly with the Python interpreter
  • json: good for reading and writing json files (good for web work)




# 상황별

1. 날짜와 시간 관련: datetime

   - https://docs.python.org/3/library/datetime.html



2. 현재의 working directory 바꾸기: os

   os.chdir(path)

   - https://docs.python.org/3/library/os.html



3. csv파일 읽기: csv

>>> import csv
>>> with open('eggs.csv', newline='') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
...     for row in spamreader:
...         print(', '.join(row))
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam

  - https://docs.python.org/3/library/csv.html



4. zip 파일 압축해제: zipfile

with ZipFile('spam.zip') as myzip:
    with myzip.open('eggs.txt') as myfile:
        print(myfile.read())

   - https://docs.python.org/3/library/zipfile.html



5. 실행시간 측정: cProfile

   - https://docs.python.org/3/library/profile.html

   - 작은 수행일때는 timeit도 많이 쓴다.

      https://docs.python.org/3/library/timeit.html



Reference:

- https://classroom.udacity.com/courses/ud1110

- https://docs.python.org/3/library/

virtualenv에 OpenAI gym 설치하기(MAC OS)



1단계: virtualenv로 가서 pip 명령을 이용해 설치한다.

$ source [설치한 경로]/bin/activate

(설치폴더이름) $ pip3 install gym

이렇게 하면 minimal 로 설치가 되며 이 단계 만으로 실행할 수 있는 환경은 다음과 같다.

- algorithmic

- toy_text

- classic_control (you'll need pyglet to render though)



끝.

2단계: atari 등은 성공하면 업데이트 예정.



reference:

https://github.com/openai/gym

# Python 언어 Syntax 요약(feat. Java)

간략히 Java를 기준으로 염두해 두어야 할 것들을 정리해본다.



0. 주석(comment)

 의미 

 Python

 비고

 한줄 주석

 # Python

 // Java

 여러줄 주석

 ''' Python '''

 """ Python """

 /* Java */



1. 연산자(Operator)

 의미

 Python

 비고

 덧셈, 뺄셈, 곱셈 나눗셈 등

 아래 나열되지 않는 대부분의 것들

 Java와 동일

 - 나눗셈을 하면 Float이 된다. Java처럼 int로 나오고 싶으면 // 이렇게 두번 쓰면 된다.

 

 제곱(거듭제곱)

 ** 라는 연산기호가 있다.

 Java에서는 Math.pow()를 사용하는 편

 연산자 Convention

 덧셈, 뺄셈같은 상대적 후순위 계산은 띄어쓰기를 하고

 곱셈, 나눗셈은 띄어쓰기 하지 않는다.

 ex) 1 + 2*3




2. 자료형

 의미 

 Python

 비고

 Integer, Float

 Integer, Float으로 double이나 short, char 같은 개념을 통합했다.

 하지만 선언시 자료형을 미리 정의하지 않는다.

 float의 경우는 2진수로 표현할 수 있는 근사값 형태로 저장되는데 이 때문에 10진수를 2진수로 변환할 때 생기는 loss가 있다.

 ex) 0.1 + 0.1 + 0.1 != 0.3

 

 Boolean

 대문자로 시작하는 True, False를 쓴다.

 하지만 선언시 자료형을 미리 정의하지 않는다.

 부정을 표현할때 "!" 대신 "not" 을 쓴다.


 String

 string(immutable)

 Java와 달리 ''로도 String을 묶을 수 있다(큰따옴표, 작은따옴표 둘다 동일하게 사용)

 특이하게도 string을 곱셈할 수 있는데 "hippo" *3 하면

"hippohippohippo" 가 된다.

 

 list

 tuple(immutable), list(mutable) 두가지 형태가 built-in으로 존재한다.

 - 서로 형변환 할 수 있다.

 1. list

 - list[start_index : end_index] 라는 구역의 개념으로 slicing과 replacing이 가능하다

 - list의 요소를 쉽게 찾아볼 수 있다.

    ex) if a in some_list:

 2. tuple

 - return 인자가 여러개 일때 이 형태로 보내주는 것이고 이렇게 Unpacking이 쉽다.

 Linked-list가 속도가 낫냐 Array-list가 낫냐 같은 결정은 그리 중요하지 않다는 뜻인가 보다...

 Set

 set 라는 명칭으로 built-in 되어 있다.

 list처럼 for 문을 돌 수 있다.

 ex) for item in set:

 이제 어떤 Set을 쓰느냐는 중요하지 않은 것이다...

 Map

 dictionary 라는 명칭으로 built-in 되어 있다.

 list처럼 for 문을 돌 수 있다.

 ex) for item in set: >> key가 하나씩 된다.

 이제 어떤 Map을 쓰느냐는 중요하지 않은 것이다...



3. Built-in Method:  built-in method로 대부분 해결이 된다.

 의미

 Python

 비고

 length

 len(): 문자열의 길이, 배열의 길이 등을 잰다

 

 type check

 type(): 자료형 type을 본다

 

 type casting

 int() 등: 자료형을 casting하고 string -> int 같은 변환도 담당한다.

 

 String 변형

 String 내부 method도 있으니 찾아서 활용하면 된다.

 - .count([찾을단어]): 찾을단어가 몇번 들어갔는지...

 - etc...

 https://docs.python.org/3/library/stdtypes.html#string-methods

 List에서 max/min 값 찾기

 max() / min()

 

 정렬

 sorted()

 Quick, Merge, Bubble 뭐 이런건 의미 없구나...

 string 배열 하나로 합치기

 [join 할때 사이에 들어갈 string].join([join시킬 string 배열])

 ex) "-".join(["This", "is", "Sparta"])

      This-is-Sparta

 - 배열에 int 같은거 들어가 있으면 오류남. string-only list

 Java에서는 StringBuilder로 해결했던 편...

 string에 단어 첫글자 대문자로 변경

 [space가 들어간 string].title()

 ex) "first last".title()

       First Last

 



4. 조건문, 반복문, brace: 이것은 예제를 보는것이 낫다.

 의미

 Python 

 Java

 brace

 특정 조건에 대한 ":" 그 밑의 탭(Indentation) 들어간 것으로 구분

 {}로 묶음

 if

 if [조건]:

 if ([조건])

 for

 for item in input_list:

 for i in range(100):

 for each 처럼 쓰거나

 for (int i = 0; i < 100; i++) 처럼 쓰거나...




Reference:

- Introduction to Python: https://www.udacity.com/course/introduction-to-python--ud1110


virtualenv에 matplotlib 설치하기(MAC OS)


1단계: virtualenv로 가서 pip 명령을 이용해 설치한다.

$ source [설치한 경로]/bin/activate

(설치폴더이름) $ pip3 install matplotlib

이렇게 하면 알아서 depentent library도 설치해가며 완료가 된다.



2단계: import matplotlib as plt 해도 에러가 난다.

Traceback (most recent call last):

  File "/Users/[user]/workspace/learning_TensorFlow/cpu_python3/learning_lab3_1.py", line 3, in <module>

    import matplotlib.pyplot as plt

  File "/Users/[user]/tf_py_3/lib/python3.6/site-packages/matplotlib/pyplot.py", line 115, in <module>

    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()

  File "/Users/[user]/tf_py_3/lib/python3.6/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup

    globals(),locals(),[backend_name],0)

  File "/Users/[user]/tf_py_3/lib/python3.6/site-packages/matplotlib/backends/backend_macosx.py", line 19, in <module>

    from matplotlib.backends import _macosx

RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. If you are using (Ana)Conda please install python.app and replace the use of 'python' with 'pythonw'. See 'Working with Matplotlib on OSX' in the Matplotlib FAQ for more information.

설치를 했는데 이건 또 뭔가...

이건 https://github.com/dsmbgu8/image_annotate.py/issues/4 에 잘 나와있다.

3단계에서 해결해보자.



3단계: matplotlib의 backend를 변경해준다.

1) 스크립트 상에서

import matplotlib

matplotlib.use('TkAgg')

import matplotlib.pyplot as plt


2) virtualenv bash 상에서

(설치폴더이름) $ echo "backend: TkAgg" >> ~/.matplotlib/matplotlibrc



4단계: matplotlib의 backend가 뭐길래...

- Graph등을 그릴때 Python을 실행하는 환경에 대한 지원을 해주는 부분이고 이것을 입맛대로 골라서 쓰면된다.

  설명대로라면 어떤이는 콘솔에서 띄우고 싶고, 어떤이는 툴에서 띄우고 싶고, 어떤이는 서버에서 띄우고...

  이런 다양한 환경을 지원하는 것이 "backend" 라고 한단다.

- 다양한 backend는 https://matplotlib.org/faq/usage_faq.html 에서 확인할 수 있다.



Reference

- https://github.com/dsmbgu8/image_annotate.py/issues/4

- https://stackoverflow.com/questions/29433824/unable-to-import-matplotlib-pyplot-as-plt-in-virtualenv

- https://matplotlib.org/faq/usage_faq.html

bash 명령어로 설치한 virtualenv 독립환경 Pycharm과 연결시키기


두가지 방법이 있다.

1. Pycharm으로 virtualenv 독립환경을 생성

2. 이미 만들어진 virtualenv 독립환경을 Pycharm으로 가져오기


1번은 당연하고

2번도 당연하지만 필자에겐 생소해서 정리해 본다.


# Pycharm > Preference > Project:your_project > Project Interpreter > 원하는 Interpreter를 선택



끝.

+ Recent posts