====== Python ======
{{tag>software_development python 개발 분석}}
* Numpy, Pandas 책링크
* [[https://wikidocs.net/book/1|점프투 파이썬]]
* [[https://wikidocs.net/book/110|파이썬을 이용한 시스템 트레이딩]]
* [[http://automatetheboringstuff.com/|Automate the Boring Stuff with Python]]
* Notepad++ 에서 Python 사용하기
* [[http://bryan7.tistory.com/275|NppExec Plugin 사용]] : Ctrl+F6 → python "$(FULL_CURRENT_PATH)"
* [[https://sourceforge.net/p/npp-plugins/discussion/672146/thread/6ca78e8a/|64bit 버전에서는 Dev버전 따로 설치해야함]]
* Python 환경변수 설정 [[http://godrjsmgl.tistory.com/30|http://godrjsmgl.tistory.com/30]]
* 확인하려면 cmd창에서 echo %PATH% : 껐다가 키면 됨
* PyCharm 에서 Error:Cannot start process, the path specified for working directory is not a directory
* File > Settings > Build, Execution, Deployment > Console > Python Console > Working Directory
* [[https://www.slideshare.net/zzonee/2018-pycon-kr-data-feature?from_action=save|[PyCon KR 2018] 땀내를 줄이는 Data와 Feature 다루기]]
* [[https://www.slideshare.net/plusjune/ss-110416117|[PyCon KR 2018] Python을 이용한 RPA]]
* [[https://stackoverflow.com/questions/51996547/upgrade-pip-to-ver18-on-anaconda|pip upgrade in acaconda ]]
conda config --add channels conda-forge conda update pip conda install pip=18.0
https://pleasebetrue.tistory.com/839
conda update --all
* [[https://mingrammer.com/underscore-in-python/|python에서 _(under score) 의 의미]] : 무시
* [[https://stackoverflow.com/questions/48587441/is-nvidia-geforce-gt-635m-suitable-for-deep-learning|deep learning 용 GPU..]]
* 잡깐 멈추고 싶을 때… input 쓰기
===== Tips =====
* range 대신 enumerate
scores = [54,67,48,99,27]
for i, score in enumerate(scores):
print(i, score)
* 1line if else
c = dosomething if status else dosomething
* Jupyter에서 image 복사하기 : Right Click on image and select "Create New View for Output" A new image file will appear.
===== Library =====
[[https://www.slideshare.net/mobile/plusjune/ss-110416117|엑셀 대신 파이썬]]
==== Pandas ====
[[software_development:python_pandas]]
==== selenium ====
[[software_development:python_selenium]]
==== File 다루기 ====
import os
#폴더 내 파일 리스트
[f for f in os.listdir(pathOfFile) if os.path.isfile(pathOfFile+'\\'+f)]
#파일 생성시간
import datetime
ctime = datetime.date.fromtimestamp(os.path.getctime(pathOfFile+'\\'+file))
#최신파일
path = pathOfFile + '\\'
files = os.listdir(path)
paths = [os.path.join(path, basename) for basename in files]
return datetime.date.fromtimestamp(os.path.getctime(max(paths, key=os.path.getctime))).strftime('%Y-%m-%d')
==== Openpyxl ====
* 기존 엑셀파일 불러올 때는 image load가 다 안될 수 있음 [[https://bitbucket.org/openpyxl/openpyxl/issues/189/image-insert-in-excel-erases-existing#comment-23793200|https://bitbucket.org/openpyxl/openpyxl/issues/189/image-insert-in-excel-erases-existing#comment-23793200]]
from win32com.client import DispatchEx
excel = DispatchEx('Excel.Application')
wbG = excel.Workbooks.Open(path_template)
wbP = excel.Workbooks.Open(path_created)
wbG.Worksheets("VIEW").Copy(Before=wbP.Worksheets("raw_homepage"))
wbP.SaveAs(path_created)
excel.Quit()
del excel # ensure Excel process ends
==== win32com.client ====
* 엑셀 저장/안저장 종료하기 [[https://stackoverflow.com/questions/6337595/python-win32-com-closing-excel-workbook|https://stackoverflow.com/questions/6337595/python-win32-com-closing-excel-workbook]]
==== Folium ====
지도 그리기
[[software_development:python_folium_map]]
==== datetime ====
from datetime import datetime, timedelta
yesterday = (datetime.today() - timedelta(1)).date()
startDate = datetime(2019, 3, 18).strftime("%Y-%m-%d")
#startDate = yesterday-timedelta(4) if yesterday.weekday()==6 else yesterday
==== Tensorflow ====
* Tensorboard UTF-8 에러 : PC이름에 한글이 있으면 안됨
==== SQLite3 ===
import sqlite3
con = sqlite3.connect(path['DB']+info_file['DB'])
cursor = self.con.cursor()
cursor.execute("SELECT name from sqlite_master where type= 'table'")
cursor.execute("""
insert into Finance (src, code, account, year, quarter, value, std, sheet, settlement, period)
select src, code, account, year, quarter, value, std, sheet, settlement, period from tmp
""")
con.commit()
print(cursor.fetchall())
con.close()
#PANDAS
df = pd.read_sql("select ... ", con)
df.to_sql('TABLE NAME', con=con, if_exists='append', index=False)
==== Pyinstaller ====
=== in Pycharm ===
https://python-forum.io/Thread-Using-PyInstaller-in-PyCharm
Adding Pyinstaller to PyCharm can be done by adding it as an external tool:
Adding tool:
------------
In Pycharm - File->Settings->Tools->External Tools
Click on the '+' sign to add a new tool (if it is the first tool you add, just fill the form, no need for the '+')
Fill the fields:
Name: Pyinstaller
Description: Generate a single executable
Program: C:\Users\[your_user_here]\AppData\Roaming\Python\Scripts\pyinstaller.exe (Make sure that Pyinstaller is recognized in PyCharm Project...)
Arguments: --onefile $FilePath$
Working directory: $FileDir$
Using the tool
--------------
In PyCharm: Tools->External Tools->Pyinstaller
The exe file will appear on a dist subfolder of the .py file folder
=== Add Data ===
자동으로 데이터들을 끌어오지 못하면 Pyinstaller 실행시 생기는 spec 파일 datas 를 추가해주어야 함
실행은 ''pyinstaller --onefile /FILE.spec''
a = Analysis(['C:\\Users\\prgra\\PycharmProjects\\news\\news_tokenize.py'],
pathex=['C:\\Users\\prgra\\PycharmProjects\\news'],
binaries=[],
datas=[], #################### HERE
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
* [[https://github.com/amueller/word_cloud/issues/381|Wordcloud]] : [ ('stopwords', 'wordcloud') ]
* [[https://www.bountysource.com/issues/47639825-pyinstaller|Konlpy]] : datas=[("파이썬경로/Python35-32/Lib/site-packages/konlpy/", "./konlpy"),
("파이썬경로/Python35-32/Lib/site-packages/konlpy/java/", "./konlpy/java"),
("파이썬경로/Python35-32/Lib/site-packages/konlpy/data/tagset/*", "./konlpy/data/tagset"),],
{{:software_development:pasted:20200215-233605.png}}
~~DISCUSSION~~