├── BeautifulSoup ├── .ipynb_checkpoints │ └── BeautifulSoup-checkpoint.ipynb └── BeautifulSoup.ipynb ├── Globals_and_Locals ├── .ipynb_checkpoints │ └── locals_&_globals_Learning-checkpoint.ipynb ├── images │ ├── image1.PNG │ ├── image2.PNG │ ├── image3.PNG │ └── image4.PNG ├── locals_&_globals_Learning.ipynb └── 給自己的Python小筆記 Python進階用法- 想讓變數名稱跟著迴圈動態定義嗎- Locals與Globals 技巧教學.md ├── README.md ├── argparse ├── images │ ├── argparse1.PNG │ ├── argparse2.PNG │ └── argparse3.PNG ├── learning_argparse.py └── readme.md ├── class ├── class_learning.py ├── class_learning1.py └── class_property_learning.py ├── delete-folder-file ├── .ipynb_checkpoints │ └── delete_file_folder-checkpoint.ipynb ├── Python-Delete-File-Folder.md ├── delete_file_folder.ipynb ├── images │ └── 1.PNG └── sample │ ├── not_null │ ├── python_file.py │ ├── sample.txt │ ├── sample_file.txt │ ├── sample_file1.txt │ └── sample_file_example.txt │ ├── python_file.py │ ├── sample.txt │ ├── sample_file.txt │ ├── sample_file1.txt │ └── sample_file_example.txt ├── eval ├── .ipynb_checkpoints │ └── eval-checkpoint.ipynb ├── eval.ipynb └── eval.md ├── excel_operation ├── read_csv │ └── 給自己的Python小筆記 - 導入CSV檔 - pandas.read_csv()參數說明.md └── read_excel │ ├── data │ └── dataset_example.xlsx │ ├── images │ ├── image1.PNG │ ├── image10.PNG │ ├── image11.PNG │ ├── image12.PNG │ ├── image13.PNG │ ├── image14.PNG │ ├── image15.PNG │ ├── image16.PNG │ ├── image17.PNG │ ├── image18.png │ ├── image19.png │ ├── image2.PNG │ ├── image20.PNG │ ├── image21.PNG │ ├── image23.PNG │ ├── image28.PNG │ ├── image3.PNG │ ├── image4.PNG │ ├── image5.PNG │ ├── image6.PNG │ ├── image7.PNG │ ├── image8.PNG │ └── image9.PNG │ ├── read_excel_learning.ipynb │ └── 給自己的Python小筆記 - 數據處理必備技能 - 將外部數據集Excel檔轉成可操作的DataFrame - read_csv() 參數詳細介紹與教學.md ├── interpolate ├── .ipynb_checkpoints │ └── interpolate-checkpoint.ipynb ├── images │ ├── 1.PNG │ ├── 2.PNG │ ├── 3.PNG │ ├── 4.PNG │ ├── 5.PNG │ ├── 6.PNG │ ├── 7.PNG │ └── 8.PNG ├── interpolate-method.md └── interpolate.ipynb ├── matplotlib └── concept │ ├── .ipynb_checkpoints │ └── matplotlib_concept-checkpoint.ipynb │ ├── [程式觀念] 大家都會使用plt畫圖,但是你真的知道plt ax fig是什麼嗎怎麼用.md │ ├── images │ ├── image1.PNG │ ├── image2.PNG │ ├── image3.PNG │ ├── image4.PNG │ ├── image5.PNG │ ├── image6.PNG │ ├── step1.PNG │ ├── step2.PNG │ ├── step3.PNG │ └── step4.PNG │ └── matplotlib_concept.ipynb ├── multi_threading ├── multi_threading.ipynb └── 給自己的Python小筆記-Python-想同時執行多個Function函數嗎 那來試試這個平行設計模組- 多執行緒(Multi-Threading)使用教學.md ├── numpy_read-write-file ├── .ipynb_checkpoints │ └── numpy_read_write_file-checkpoint.ipynb ├── NumPy如何讀寫檔案.md ├── example.txt ├── example1.txt ├── images │ └── 1.PNG ├── multiple_array.npz ├── numpy_read_write_file.ipynb ├── numpy_sample.npy └── numpy_samplel.npy ├── parse ├── .ipynb_checkpoints │ └── learning_parse-checkpoint.ipynb ├── images │ ├── compile().PNG │ ├── findall().PNG │ ├── parse().PNG │ └── search().PNG ├── learning_parse.ipynb └── readme.md ├── pathlib ├── Readme.md ├── data │ ├── test.txt │ └── test3.txt ├── files │ ├── b.txt │ ├── c.csv │ ├── d.docx │ ├── e.csv │ └── f.csv └── pathlib.ipynb ├── pytest-fixture ├── __pycache__ │ └── test_fixture_learning.cpython-37-pytest-5.4.3.pyc └── test_fixture_learning.py ├── pytest ├── __pycache__ │ ├── test_pytest_learning_function-except.cpython-37-pytest-5.4.3.pyc │ └── test_pytest_learning_function.cpython-37-pytest-5.4.3.pyc ├── test │ ├── test_a_2.py │ └── test_b_1.py ├── test_pytest_learning_function-except.py └── test_pytest_learning_function.py ├── regular_expression ├── .ipynb_checkpoints │ └── regular_expression-checkpoint.ipynb ├── images │ ├── image1.png │ ├── image10.png │ ├── image11.png │ ├── image12.PNG │ ├── image13.PNG │ ├── image2.png │ ├── image3.png │ ├── image4.png │ ├── image5.png │ ├── image6.png │ ├── image7.png │ ├── image8.png │ └── image9.png ├── regular_expression.ipynb ├── 給自己的Python小筆記 - 強大的數據處理工具 - 正則表達式 - Regular Expression - regex詳細教學.md └── 表格.pptx ├── searchsorted ├── .ipynb_checkpoints │ └── searchsorted-checkpoint.ipynb ├── NumPy-Searchsorted-Method.md ├── images │ ├── 1.PNG │ └── 2.PNG └── searchsorted.ipynb ├── selenium ├── .ipynb_checkpoints │ └── selenium-learning-checkpoint.ipynb ├── chromedriver.exe ├── debug.log ├── driver │ └── chromedriver.exe └── selenium-learning.ipynb ├── simplehttpserver_learning ├── __pycache__ │ └── httpserver.cpython-37.pyc ├── httpserver.py ├── httpserver_learning.md └── images │ ├── image1.PNG │ ├── image2.PNG │ ├── image3.PNG │ ├── image4.PNG │ ├── image5.PNG │ └── image6.PNG ├── sphinx ├── python-project │ ├── doc │ │ ├── Makefile │ │ ├── build │ │ │ ├── doctrees │ │ │ │ ├── Example.doctree │ │ │ │ ├── environment.pickle │ │ │ │ └── index.doctree │ │ │ └── html │ │ │ │ ├── .buildinfo │ │ │ │ ├── Example.html │ │ │ │ ├── _sources │ │ │ │ ├── Example.rst.txt │ │ │ │ └── index.rst.txt │ │ │ │ ├── _static │ │ │ │ ├── basic.css │ │ │ │ ├── darkmetal.png │ │ │ │ ├── doctools.js │ │ │ │ ├── documentation_options.js │ │ │ │ ├── file.png │ │ │ │ ├── headerbg.png │ │ │ │ ├── jquery-3.5.1.js │ │ │ │ ├── jquery.js │ │ │ │ ├── language_data.js │ │ │ │ ├── logo.png │ │ │ │ ├── metal.png │ │ │ │ ├── minus.png │ │ │ │ ├── navigation.png │ │ │ │ ├── plus.png │ │ │ │ ├── print.css │ │ │ │ ├── pygments.css │ │ │ │ ├── scrolls.css │ │ │ │ ├── searchtools.js │ │ │ │ ├── theme_extras.js │ │ │ │ ├── underscore-1.3.1.js │ │ │ │ ├── underscore.js │ │ │ │ ├── watermark.png │ │ │ │ └── watermark_blur.png │ │ │ │ ├── genindex.html │ │ │ │ ├── index.html │ │ │ │ ├── objects.inv │ │ │ │ ├── search.html │ │ │ │ └── searchindex.js │ │ ├── make.bat │ │ └── source │ │ │ ├── Example.rst │ │ │ ├── conf.py │ │ │ └── index.rst │ └── src │ │ ├── Example.py │ │ └── __pycache__ │ │ └── Example.cpython-37.pyc └── sphinx_more │ └── Readme.md ├── variable ├── Readme.md ├── images │ ├── .DS_Store │ ├── Untitled 1.png │ ├── Untitled 2.png │ ├── Untitled.png │ └── Untitled3.png └── variable_practice.ipynb ├── virtual_environment ├── Readme.md └── images │ ├── image1.PNG │ ├── image2.PNG │ ├── image3.PNG │ ├── image4.PNG │ ├── image5.PNG │ ├── image6.PNG │ ├── image7.PNG │ └── image8.PNG └── werkzeug.security └── werkzeug.security_learning.py /Globals_and_Locals/.ipynb_checkpoints/locals_&_globals_Learning-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 4 6 | } 7 | -------------------------------------------------------------------------------- /Globals_and_Locals/images/image1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/Globals_and_Locals/images/image1.PNG -------------------------------------------------------------------------------- /Globals_and_Locals/images/image2.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/Globals_and_Locals/images/image2.PNG -------------------------------------------------------------------------------- /Globals_and_Locals/images/image3.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/Globals_and_Locals/images/image3.PNG -------------------------------------------------------------------------------- /Globals_and_Locals/images/image4.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/Globals_and_Locals/images/image4.PNG -------------------------------------------------------------------------------- /Globals_and_Locals/locals_&_globals_Learning.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## 一般的作法,我們會分別定義每個變數的值,然後再使用它們" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 2, 13 | "metadata": {}, 14 | "outputs": [ 15 | { 16 | "name": "stdout", 17 | "output_type": "stream", 18 | "text": [ 19 | "1\n", 20 | "2\n", 21 | "3\n", 22 | "4\n", 23 | "5\n", 24 | "6\n", 25 | "7\n", 26 | "8\n", 27 | "9\n", 28 | "10\n" 29 | ] 30 | } 31 | ], 32 | "source": [ 33 | "number1 = 1\n", 34 | "number2 = 2\n", 35 | "number3 = 3\n", 36 | "number4 = 4\n", 37 | "number5 = 5\n", 38 | "number6 = 6\n", 39 | "number7 = 7\n", 40 | "number8 = 8\n", 41 | "number9 = 9\n", 42 | "number10 = 10\n", 43 | "\n", 44 | "\n", 45 | "print(number1)\n", 46 | "print(number2)\n", 47 | "print(number3)\n", 48 | "print(number4)\n", 49 | "print(number5)\n", 50 | "print(number6)\n", 51 | "print(number7)\n", 52 | "print(number8)\n", 53 | "print(number9)\n", 54 | "print(number10)" 55 | ] 56 | }, 57 | { 58 | "cell_type": "markdown", 59 | "metadata": {}, 60 | "source": [ 61 | "## locals與globals簡單變換變數名稱的運用" 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": 5, 67 | "metadata": {}, 68 | "outputs": [ 69 | { 70 | "name": "stdout", 71 | "output_type": "stream", 72 | "text": [ 73 | "Print In Once: 1\n", 74 | "Print In Once: 2\n", 75 | "Print In Once: 3\n", 76 | "Print In Once: 4\n", 77 | "Print In Once: 5\n", 78 | "Print In Once: 6\n", 79 | "Print In Once: 7\n", 80 | "Print In Once: 8\n", 81 | "Print In Once: 9\n" 82 | ] 83 | } 84 | ], 85 | "source": [ 86 | "for i in range(1,10):\n", 87 | " locals()['number'+str(i)] = i\n", 88 | " print('Print In Once: ', locals()['number'+str(i)])\n", 89 | " " 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": 6, 95 | "metadata": {}, 96 | "outputs": [ 97 | { 98 | "name": "stdout", 99 | "output_type": "stream", 100 | "text": [ 101 | "Print In Once: 1\n", 102 | "Print In Once: 2\n", 103 | "Print In Once: 3\n", 104 | "Print In Once: 4\n", 105 | "Print In Once: 5\n", 106 | "Print In Once: 6\n", 107 | "Print In Once: 7\n", 108 | "Print In Once: 8\n", 109 | "Print In Once: 9\n", 110 | "1\n", 111 | "2\n", 112 | "3\n", 113 | "4\n", 114 | "5\n", 115 | "6\n", 116 | "7\n", 117 | "8\n", 118 | "9\n" 119 | ] 120 | } 121 | ], 122 | "source": [ 123 | "for i in range(1,10):\n", 124 | " globals()['number'+str(i)] = i\n", 125 | " print('Print In Once: ', globals()['number'+str(i)])\n", 126 | " \n", 127 | "print(number1)\n", 128 | "print(number2)\n", 129 | "print(number3)\n", 130 | "print(number4)\n", 131 | "print(number5)\n", 132 | "print(number6)\n", 133 | "print(number7)\n", 134 | "print(number8)\n", 135 | "print(number9)" 136 | ] 137 | }, 138 | { 139 | "cell_type": "markdown", 140 | "metadata": {}, 141 | "source": [ 142 | "## locals: 宣告為區域變數,它在使用上會遇到一個問題,在函式A中定義好的變數,不能在函式B中被使用" 143 | ] 144 | }, 145 | { 146 | "cell_type": "code", 147 | "execution_count": 2, 148 | "metadata": {}, 149 | "outputs": [ 150 | { 151 | "name": "stdout", 152 | "output_type": "stream", 153 | "text": [ 154 | "Jack\n", 155 | "Eric\n", 156 | "Cathy\n", 157 | "Jenny\n", 158 | "James\n", 159 | "Gary\n", 160 | "Lucy\n", 161 | "Candy\n" 162 | ] 163 | }, 164 | { 165 | "ename": "KeyError", 166 | "evalue": "'name0'", 167 | "output_type": "error", 168 | "traceback": [ 169 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 170 | "\u001b[1;31mKeyError\u001b[0m Traceback (most recent call last)", 171 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 13\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0m__name__\u001b[0m \u001b[1;33m==\u001b[0m \u001b[1;34m'__main__'\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 14\u001b[0m \u001b[0mlocals_example\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 15\u001b[1;33m \u001b[0mgreet_example\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", 172 | "\u001b[1;32m\u001b[0m in \u001b[0;36mgreet_example\u001b[1;34m()\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0mgreet_example\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 9\u001b[0m \u001b[1;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mlen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mname_list\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 10\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'locals(): Hello'\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0mlocals\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'name'\u001b[0m\u001b[1;33m+\u001b[0m\u001b[0mstr\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 11\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 12\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n", 173 | "\u001b[1;31mKeyError\u001b[0m: 'name0'" 174 | ] 175 | } 176 | ], 177 | "source": [ 178 | "name_list = ['Jack', 'Eric', 'Cathy', 'Jenny', 'James', 'Gary', 'Lucy', 'Candy']\n", 179 | "\n", 180 | "def locals_example():\n", 181 | " for i in range(len(name_list)):\n", 182 | " locals()['name'+str(i)] = name_list[i]\n", 183 | " print(locals()['name'+str(i)])\n", 184 | "\n", 185 | "def greet_example():\n", 186 | " for i in range(len(name_list)):\n", 187 | " print('locals(): Hello' + locals()['name'+str(i)])\n", 188 | " \n", 189 | " \n", 190 | "if __name__ == '__main__':\n", 191 | " locals_example()\n", 192 | " greet_example()\n" 193 | ] 194 | }, 195 | { 196 | "cell_type": "markdown", 197 | "metadata": {}, 198 | "source": [ 199 | "## globals: 宣告為全域變數,變數就能在任何其他函數中使用" 200 | ] 201 | }, 202 | { 203 | "cell_type": "code", 204 | "execution_count": 3, 205 | "metadata": {}, 206 | "outputs": [ 207 | { 208 | "name": "stdout", 209 | "output_type": "stream", 210 | "text": [ 211 | "Jack\n", 212 | "Eric\n", 213 | "Cathy\n", 214 | "Jenny\n", 215 | "James\n", 216 | "Gary\n", 217 | "Lucy\n", 218 | "Candy\n", 219 | "globals(): HelloJack\n", 220 | "globals(): HelloEric\n", 221 | "globals(): HelloCathy\n", 222 | "globals(): HelloJenny\n", 223 | "globals(): HelloJames\n", 224 | "globals(): HelloGary\n", 225 | "globals(): HelloLucy\n", 226 | "globals(): HelloCandy\n", 227 | "Cathy\n" 228 | ] 229 | } 230 | ], 231 | "source": [ 232 | "name_list = ['Jack', 'Eric', 'Cathy', 'Jenny', 'James', 'Gary', 'Lucy', 'Candy']\n", 233 | "\n", 234 | "def globals_example():\n", 235 | " for n in range(len(name_list)):\n", 236 | " globals()['name'+str(n)] = name_list[n]\n", 237 | " print(globals()['name'+str(n)])\n", 238 | "\n", 239 | "def greet_example():\n", 240 | " for n in range(len(name_list)):\n", 241 | " print('globals(): Hello' + globals()['name'+str(n)])\n", 242 | " \n", 243 | " \n", 244 | "if __name__ == '__main__':\n", 245 | " globals_example()\n", 246 | " greet_example()\n", 247 | " print(name2)" 248 | ] 249 | } 250 | ], 251 | "metadata": { 252 | "kernelspec": { 253 | "display_name": "Python 3", 254 | "language": "python", 255 | "name": "python3" 256 | }, 257 | "language_info": { 258 | "codemirror_mode": { 259 | "name": "ipython", 260 | "version": 3 261 | }, 262 | "file_extension": ".py", 263 | "mimetype": "text/x-python", 264 | "name": "python", 265 | "nbconvert_exporter": "python", 266 | "pygments_lexer": "ipython3", 267 | "version": "3.7.6" 268 | } 269 | }, 270 | "nbformat": 4, 271 | "nbformat_minor": 4 272 | } 273 | -------------------------------------------------------------------------------- /Globals_and_Locals/給自己的Python小筆記 Python進階用法- 想讓變數名稱跟著迴圈動態定義嗎- Locals與Globals 技巧教學.md: -------------------------------------------------------------------------------- 1 | # 給自己的Python小筆記: Python進階用法- 想讓變數名稱跟著迴圈動態定義嗎- Locals與Globals 技巧教學 2 | 3 | 4 | 5 | 哈囉哈囉,今天想跟大家介紹一個我在工作中常用到的一個小技巧,由於職業的關係,我時常需要導入數據,並賦予不同的變數名稱來同時操作這些不同時間點錄下的資料,但如果想要同時對這種眾多檔案進行一樣的數據處理,總不能要我一個一個定義變數名稱給它們,然後再一個一個進行數據處理,這樣我就沒時間回家寫文章了XD,所以今天要來分享給大家這個,我覺得非常實用的技巧 6 | 7 | 8 | 9 | 10 | 11 | ## 問題1: 如果今天遇到一個需要我們定義很多連續變數的值時,我們該怎麼做呢? 12 | 13 | 14 | 15 | 16 | 17 | #### 範例1: 一般的作法,我們會分別定義每個變數的值,然後再使用它們 18 | 19 | ```Python 20 | number1 = 1 21 | number2 = 2 22 | number3 = 3 23 | number4 = 4 24 | number5 = 5 25 | number6 = 6 26 | number7 = 7 27 | number8 = 8 28 | number9 = 9 29 | number10 = 10 30 | 31 | 32 | print(number1) 33 | print(number2) 34 | print(number3) 35 | print(number4) 36 | print(number5) 37 | print(number6) 38 | print(number7) 39 | print(number8) 40 | print(number9) 41 | print(number10) 42 | ``` 43 | 44 | ![image1](images\image1.PNG) 45 | 46 | 47 | 48 | **小提醒: 這樣的作法,確實也可以達到我們要的目的,但是如果今天變數一變多,我們有1000個以上的時候,總不能這樣慢慢定義每個變數,會寫到天荒地老,哈哈,所以接下來我們就來看看今天的主角: locals()與globals()如何幫助我們快速實現目的** 49 | 50 | 51 | 52 | #### 範例2: locals與globals簡單變換變數名稱的運用 53 | 54 | + locals() 55 | 56 | 57 | 58 | ```Python 59 | for i in range(1,10): 60 | locals()['number'+str(i)] = i 61 | print('Print In Once: ', locals()['number'+str(i)]) 62 | ``` 63 | 64 | 65 | 66 | 67 | 68 | + globals() 69 | 70 | 71 | 72 | ```Python 73 | for i in range(1,10): 74 | globals()['number'+str(i)] = i 75 | print('Print In Once: ', globals()['number'+str(i)]) 76 | 77 | print(number1) 78 | print(number2) 79 | print(number3) 80 | print(number4) 81 | print(number5) 82 | print(number6) 83 | print(number7) 84 | print(number8) 85 | print(number9) 86 | ``` 87 | 88 | ![image2](images\image2.PNG) 89 | 90 | 91 | 92 | 93 | 94 | ## 問題2: 如果今天在函式中定義好的變數,要怎麼在另一個函式中此用這些變數呢? 95 | 96 | 97 | 98 | **從上面的結果看起來,不論是locals()還是globals(),都能達到一樣的效果呀,那它們有什麼不同?** 99 | 100 | + locals(): 宣告為區域變數,它在使用上會遇到一個問題,在函式A中定義好的變數,不能在函式B中被使用 101 | 102 | ```Python 103 | name_list = ['Jack', 'Eric', 'Cathy', 'Jenny', 'James', 'Gary', 'Lucy', 'Candy'] 104 | 105 | def locals_example(): 106 | for i in range(len(name_list)): 107 | locals()['name'+str(i)] = name_list[i] 108 | print(locals()['name'+str(i)]) 109 | 110 | def greet_example(): 111 | for n in range(len(name_list)): 112 | print('locals(): Hello' + locals()['name'+str(i)]) 113 | 114 | 115 | if __name__ == '__main__': 116 | locals_example() 117 | greet_example() 118 | ``` 119 | 120 | 121 | 122 | 123 | 124 | ![image3](images\image3.PNG) 125 | 126 | **從最後結果發現,num0並不能在本身函式以外的地方使用,這也正是locals()宣告為區域變數的原因** 127 | 128 | 129 | 130 | + globals(): 宣告為全域變數,變數就能在任何其他函數中使用 131 | 132 | ```Python 133 | name_list = ['Jack', 'Eric', 'Cathy', 'Jenny', 'James', 'Gary', 'Lucy', 'Candy'] 134 | 135 | def globals_example(): 136 | for n in range(len(name_list)): 137 | globals()['name'+str(n)] = name_list[n] 138 | print(globals()['name'+str(n)]) 139 | 140 | def greet_example(): 141 | for n in range(len(name_list)): 142 | print('globals(): Hello' + globals()['name'+str(n)]) 143 | 144 | 145 | if __name__ == '__main__': 146 | globals_example() 147 | greet_example() 148 | print(name2) 149 | ``` 150 | 151 | 152 | 153 | ![image4](images\image4.PNG) 154 | 155 | 156 | 157 | 從最後結果可以看出,由於name2是被globals()宣告為全域變數的,所以最後可以成功印出 158 | 159 | 160 | 161 | ## 既然globals()這麼好用,那全部都用globals就好啦,為什麼還要使用locals呢? 162 | 163 | 未來當撰寫的程式碼越來越多的時候,可能會出現重複定義同一個變數名稱,就有覆寫的問題,所以要斟酌使用locals或是globals喔 164 | 165 | 166 | 167 | 168 | 169 | **這篇雖然短短的,但我覺得這個技巧是可以幫助我們節省很長很長的時間,來進行數據處理,希望這次對大家也有大大的幫助~~** 170 | 171 | **如果覺得我寫得還行,再幫我拍拍手喔,感謝您** 172 | 173 | 174 | 175 | 176 | 177 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Learn-Python- 2 | sharing and learning python skills 3 | 4 | + parse 5 | + argparse 6 | 7 | -------------------------------------------------------------------------------- /argparse/images/argparse1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/argparse/images/argparse1.PNG -------------------------------------------------------------------------------- /argparse/images/argparse2.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/argparse/images/argparse2.PNG -------------------------------------------------------------------------------- /argparse/images/argparse3.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/argparse/images/argparse3.PNG -------------------------------------------------------------------------------- /argparse/learning_argparse.py: -------------------------------------------------------------------------------- 1 | ## learning_argparse.py 2 | 3 | 4 | ## import package 5 | from argparse import ArgumentParser 6 | 7 | ## Introduce 8 | 9 | ##parameter 10 | ## prog : program name 11 | ## usage : how to use your program (default=None, it will replace with your program name) 12 | ## description: describe about your program 13 | ## epilog: additional materials 14 | parser1 = ArgumentParser(prog = "my argparse example", usage = None, 15 | description = "learn how to use argparse", 16 | epilog = "https://github.com/chwang12341/Learn-Python-") 17 | # print(parser1) 18 | 19 | ##ArgumentParser(prog='my argparse example', 20 | ##usage=None, 21 | ##description='learn how to use argparse', 22 | ##formatter_class=, 23 | ##conflict_handler='error', 24 | ##add_help=True) 25 | 26 | 27 | # print(parser1.print_help()) 28 | ##usage: my argparse example [-h] 29 | 30 | ##learn how to use argparse 31 | 32 | ##optional arguments: 33 | ## -h, --help show this help message and exit 34 | ## 35 | ##https://github.com/chwang12341/Learn-Python- 36 | ##None 37 | 38 | ## Example 39 | ## import package 40 | ## from argparse import ArgumentParser 41 | 42 | parser = ArgumentParser() 43 | ## add static parameters (type=int, str) 44 | parser.add_argument('runtimes', type=int, help='display an integer') 45 | parser.add_argument('name', type=str, help='display a string') 46 | 47 | ## add Optional parameters 48 | ## dest: after parsing, the variable name 49 | parser.add_argument('--place', type=str, help='display an integer', dest = 'position') 50 | parser.add_argument('--food', type=str, help='display an integer') 51 | 52 | args = parser.parse_args() 53 | ## print variable 54 | # print (args.runtimes) 55 | # print (args.name) 56 | 57 | ## function 58 | def count(runtimes,name): 59 | for i in range(runtimes): 60 | print(str(name)+' run ' + str(i) +' times' ) 61 | 62 | 63 | ##execute function 64 | if __name__ == "__main__": 65 | ## Optional parameters 66 | if args.position: 67 | print('Place: '+ args.position) 68 | if args.food: 69 | print('food: '+ args.food) 70 | 71 | ## static parameters 72 | count(args.runtimes, args.name) -------------------------------------------------------------------------------- /argparse/readme.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Argparse 4 | 5 | **for controling variable through external ** 6 | 7 | 8 | 9 | ### Import Packages 10 | 11 | import argparse 12 | 13 | 14 | 15 | ### Introduction 16 | 17 | ArgumentParser() parameter: 18 | 19 | + prog : program name 20 | 21 | + usage : how to use your program (default=None, it will replace with your program name) 22 | 23 | + description: describe about your program 24 | 25 | + epilog: additional materials 26 | 27 | ![argparse1](https://github.com/chwang12341/Learn-Python-/blob/master/argparse/images/argparse1.PNG?raw=true) 28 | 29 | 30 | 31 | ### Example 32 | 33 | 1. Optional parameters 34 | 35 | + control variable (ex.args.runtimes) 36 | + type: int 、str 37 | 38 | 2. Additional parameters 39 | 40 | you can choose to give the paremeter or not 41 | 42 | + use "--" to form addtional parameters 43 | 44 | + deset: after parsing, the variable name 45 | 46 | ex. add parameter: parser.add_argument('--place', type=str, help='display an integer', dest = 'position') 47 | 48 | ​ form variable name: args.position 49 | 50 | ![argparse2](https://github.com/chwang12341/Learn-Python-/blob/master/argparse/images/argparse2.PNG?raw=true) 51 | 52 | ### Execute python 53 | 54 | go to cmd and try to run your python like this 55 | 56 | 1. python learning_argparse.py 10 Shane : Static Parameter 57 | 2. python learning_argparse.py 10 Shane --place forest : Additional Parameter (**you can choose to give the paremeter or not**) 58 | 3. python learning_argparse.py 10 Shane --food meat : Additional Parameter 59 | 4. python learning_argparse.py 10 Shane --place forest --food toast : Additional Parameter 60 | 61 | ![argparse3](https://github.com/chwang12341/Learn-Python-/blob/master/argparse/images/argparse3.PNG?raw=true) 62 | 63 | 64 | 65 | *reference: * -------------------------------------------------------------------------------- /class/class_learning.py: -------------------------------------------------------------------------------- 1 | # # -*- coding: utf-8 -*- 2 | # """ 3 | # Created on Wed Jun 24 19:40:06 2020 4 | 5 | # @author: user 6 | # """ 7 | # ## Class Basic Design 8 | # class House: 9 | 10 | # def __init__(self, address, name, phone_number): 11 | # self.address = address 12 | # self.name = name 13 | # self.phone_number = phone_number 14 | # self.member = 0 15 | 16 | # def move_in(self, amount): 17 | 18 | # if amount < 0: 19 | # raise ValueError("Amazing: people amount can't be negative") 20 | # else: 21 | # self.member += amount 22 | 23 | # def move_out(self, amount): 24 | 25 | # if amount > self.member: 26 | # raise ValueError('exceed the amount of people here') 27 | # else: 28 | # self.member -= amount 29 | 30 | # def __del__(self): 31 | # return "destroy the house" 32 | # little_turtle_home = House('any Town any Street', 'Turtle', '09xx') 33 | # little_turtle_home.move_in(2) 34 | # little_turtle_home.move_in(4) 35 | # little_turtle_home.move_in(2) 36 | # little_turtle_home.move_out(2) 37 | # print(little_turtle_home.member) 38 | # del little_turtle_home 39 | # # print(little_turtle_home) 40 | # ##NameError: name 'little_turtle_home' is not defined 41 | 42 | 43 | 44 | 45 | 46 | 47 | # ## __new__ 方法 48 | # class X(object): 49 | # def __init__(self,*args,**kargs): 50 | # print ("init %s" %self.__class__) 51 | # self.total = 2 52 | # def __new__(cls,*args,**kargs): 53 | # print ("new %s" %cls) 54 | # cls.total = 4 55 | # return object.__new__(cls, *args, **kargs) 56 | 57 | # ## *num 讓我們傳入參數時,可以是tuple 58 | # def add(cls, *num): 59 | # for i in num: 60 | # print(i) 61 | # print(type(i)) 62 | # cls.total += i 63 | # print(cls.total) 64 | 65 | 66 | # x = X() 67 | # ## 先執行new 再執行init(會幫__new__初始化) 再執行add 68 | # x.add(1,4,8) 69 | # # output 70 | # # new 71 | # # init 72 | # # 1 73 | # # 74 | # # 4 75 | # # 76 | # # 8 77 | # # 78 | # # 15 79 | 80 | 81 | 82 | 83 | # ## __dict__ 用法 和 __str__用法 84 | # ## https://blog.csdn.net/qq_26442553/article/details/82466382 85 | # ## https://blog.csdn.net/xiaolewennofollow/article/details/51455185?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase 86 | # class House: 87 | # city = "HsinChu" ## class attribute(__dict__ can't load) 88 | # def __init__(self, address, name, phone_number): 89 | # self.address = address 90 | # self.name = name 91 | # self.phone_number = phone_number 92 | # self.member = 0 93 | 94 | # def __str__(self): 95 | # return ("House name: %s, Address: %s, Phone Number: %s"%(self.name,self.address,self.phone_number)) 96 | # ## 實際操作 97 | # little_turtle_home = House('any Town any Street', 'Turtle', '0999') 98 | # print(little_turtle_home) ## print type(string) ## same as print(little_turtle_home.__str__()) 99 | # ## Output 100 | # # House name: Turtle, Address: any Town any Street, Phone Number: 0999 101 | # print(little_turtle_home.__dict__) ##change to dict format 102 | # ## Out put 103 | # # {'address': 'any Town any Street', 'name': 'Turtle', 'phone_number': '0999', 'member': 0} 104 | # print(little_turtle_home.__dict__['address']) 105 | # # any Town any Street 106 | 107 | 108 | 109 | 110 | # ## __dict__ 應用 111 | 112 | 113 | # ## create a dict 114 | # class House: 115 | 116 | # def __init__(self, address, name, phone_number): 117 | # self.address = address 118 | # self.name = name 119 | # self.phone_number = phone_number 120 | 121 | # little_turtle_home = House('any Town any Street', 'Turtle', '09xx') 122 | # print(little_turtle_home.__dict__) 123 | # ## Output 124 | # #{'address': 'any Town any Street', 'name': 'Turtle', 'phone_number': '09xx'} 125 | 126 | # ## if your input is dict format 127 | # ## method1: 128 | # class House1: 129 | # def __init__(self,dict_obj): 130 | # self.address = dict_obj['address'] 131 | # self.name = dict_obj['name'] 132 | # self.phone_number = dict_obj['phone_number'] 133 | 134 | # little_turtle_home1 = House1(little_turtle_home.__dict__) 135 | # print(little_turtle_home1.name) 136 | # ## Output 137 | # #Turtle 138 | 139 | # # method2: you can use self.__dict__.update() : help you easily parse the dict into variable format 140 | # class House2: 141 | # def __init__(self,dict_obj): 142 | # self.__dict__.update(dict_obj) 143 | 144 | # little_turtle_home2 = House1(little_turtle_home.__dict__) 145 | # print(little_turtle_home2.name) 146 | # ## Output 147 | # #Turtle 148 | 149 | 150 | 151 | \ 152 | -------------------------------------------------------------------------------- /class/class_learning1.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Jul 6 22:23:50 2020 4 | 5 | @author: user 6 | """ 7 | 8 | class House: 9 | tv_amount = 1 #類別屬性 10 | def __init__(self, human, name): 11 | self.human = human ##實體屬性 12 | self.name = name ##實體屬性 13 | House.add_tv(1) ## static 14 | House.add_tv1(2) ## class 15 | 16 | @staticmethod 17 | def add_tv(i): 18 | House.tv_amount += i 19 | 20 | @classmethod 21 | def add_tv1(cls,i): 22 | cls.tv_amount += i 23 | little_turtle_home = House(1, "Turtle") 24 | print(little_turtle_home.name) # Turtle 25 | print(little_turtle_home.human) #1 26 | print(little_turtle_home.tv_amount) #4 27 | print(House.tv_amount)# 4 28 | little_turtle_home1 = House(1, "Turtle") 29 | print(little_turtle_home1.tv_amount) #7 30 | print(House.tv_amount) #7 31 | 32 | 33 | ## import abstract package 34 | import abc 35 | class old_Turtle(abc.ABC): 36 | @abc.abstractmethod 37 | def swim(self): 38 | print('I can swim') 39 | return NotImplemented 40 | 41 | class young_turtle(old_Turtle): 42 | def swim(self): 43 | print('I can swim fast') 44 | 45 | def eat(self): 46 | print('I can eat') 47 | 48 | class little_turtle(old_Turtle): 49 | def eat(self): 50 | print('I can eat') 51 | 52 | 53 | 54 | print(young_turtle().swim()) # I can swim fast 55 | print(young_turtle().eat()) # I can eat 56 | print(little_turtle().eat()) # TypeError: Can't instantiate abstract class little_turtle with abstract methods swim 57 | 58 | 59 | class House: 60 | 61 | def __init__(self, address, name, phone_number): 62 | self.__address = address 63 | self.__name = name 64 | self.phone_number = phone_number 65 | self.member = 0 66 | little_turtle_home = House('any Town any Street', 'Turtle', '09xx') 67 | print(little_turtle_home.phone_number) ## 沒封裝: 09xx 68 | print(little_turtle_home.__address) ## 有封裝: AttributeError: 'House' object has no attribute 'address' 69 | 70 | class House: 71 | 72 | def __init__(self, address, name, phone_number): 73 | self.__address = address 74 | self.__name = name 75 | self.phone_number = phone_number 76 | self.member = 0 77 | 78 | def get_attribute(self): 79 | return self.__address 80 | little_turtle_home = House('any Town any Street', 'Turtle', '09xx') 81 | print(little_turtle_home.phone_number) ## 沒封裝: 09xx 82 | # print(little_turtle_home.address) ## 有封裝: AttributeError: 'House' object has no attribute 'address' 83 | print(little_turtle_home.get_attribute()) ## 有封裝,但換個方法get起來 : any Town any Street 84 | 85 | ## 建立一個 Class 86 | class House: 87 | def __init__(self, address, name, phone_number): 88 | self.address = address 89 | self.name = name 90 | self.phone_number = phone_number 91 | ## 再建立一個class 92 | class material: 93 | def __init__(self, material): 94 | self.material = material 95 | def find(self): 96 | return "find out material!!" 97 | ## 先建立一個little_turtle_home 98 | little_turtle_home = House('any Town any Street', 'Turtle', '09xx') 99 | ## 再建立一個在little_turtle_home底下的class 100 | new_little_turtle_home = little_turtle_home.material("brick") 101 | ## 使用這個class的function 102 | print(new_little_turtle_home.find()) #find out material!! 103 | ## 查看House class 底下的資訊 104 | print(little_turtle_home.address , little_turtle_home.name, little_turtle_home.phone_number, end=' ') # any Town any Street Turtle 09xx 105 | ## 在House底下建立個另一個class material ,沒辦法用它查看外層class House的資訊 106 | # print(new_little_turtle_home.address , new_little_turtle_home.name, new_little_turtle_home.phone_number) # 'material' object has no attribute 'address' 107 | ## 使用這個class的屬性 108 | print(new_little_turtle_home.material) # brick 109 | ## 查看原本建立的class little_turtle_home 底下的class material 110 | print(little_turtle_home.material) # 111 | 112 | 113 | class House(object): 114 | pass 115 | Little_turtle_home = House() 116 | Little_turtle_home.name = 'Turtle' ## 賦予新值 117 | print(Little_turtle_home.name) #Turtle 118 | 119 | class House1(object): 120 | __slots__ = {'people_amount','phone'} 121 | pass 122 | Little_turtle_home1 = House1() 123 | # Little_turtle_home1.name = 'Turtle' # 'House1' object has no attribute 'name' 124 | Little_turtle_home1.people_amount = 1 125 | print(Little_turtle_home1.people_amount) #1 126 | Little_turtle_home1.phone = '09xx' 127 | print(Little_turtle_home1.phone) #09xx -------------------------------------------------------------------------------- /class/class_property_learning.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Jul 6 22:06:51 2020 4 | 5 | @author: user 6 | """ 7 | 8 | ## property 基本用法 (有無property的區別) 9 | class House: 10 | 11 | def __init__(self, address, name, phone_number): 12 | self.address = address 13 | self.name = name 14 | self.phone_number = phone_number 15 | 16 | @property 17 | def full_information(self): 18 | print("這是過去我們用print的方法: address:%s, name:%s, phone_number:%s" %(self.address, self.name, self.phone_number)) 19 | return "new method: address:%s, name:%s, phone_number:%s" %(self.address, self.name, self.phone_number) 20 | little_turtle_home = House('any Town any Street', 'Turtle', '09xx') 21 | print(little_turtle_home.full_information) 22 | ## 如果不加 @property print 會得到 > 23 | ## 如果加上@property print 會得到 24 | ## 這是過去我們用print的方法: address:any Town any Street, name:Turtle, phone_number:09xx 25 | ##new method: address:any Town any Street, name:Turtle, phone_number:09xx 26 | 27 | little_turtle_home.full_information = "address:any county, name:Fish, phone_number:06xx" 28 | ## AttributeError: can't set attribute 29 | 30 | class House: 31 | 32 | def __init__(self, name): 33 | self.name = name 34 | 35 | @property 36 | def full_name(self): 37 | return self.name 38 | 39 | @full_name.setter 40 | def full_name(self, value): 41 | self.name = value 42 | 43 | @full_name.deleter 44 | def full_name(self): 45 | del self.name 46 | print('have a nice day') 47 | 48 | 49 | little_turtle_home = House('Turtle') 50 | print(little_turtle_home.full_name) 51 | ## Turtle 52 | little_turtle_home.full_name = 'Fish' 53 | print(little_turtle_home.full_name) 54 | ## Fish 55 | del little_turtle_home.full_name 56 | ## have a nice day 57 | little_turtle_home.full_name = 'Star' 58 | print(little_turtle_home.full_name) 59 | ## Star -------------------------------------------------------------------------------- /delete-folder-file/.ipynb_checkpoints/delete_file_folder-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 4 6 | } 7 | -------------------------------------------------------------------------------- /delete-folder-file/Python-Delete-File-Folder.md: -------------------------------------------------------------------------------- 1 | # 給自己的Python小筆記 - 如何自動刪除檔案和資料夾? - 各種方法教學 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | ## 1. 總表 - 刪除檔案與資料夾的方法比較 10 | 11 | 12 | 13 | |方法|模組|說明| 14 | |---|---|---| 15 | |os.remove()|os|刪除檔案| 16 | |os.unlink()|os|刪除檔案| 17 | |rmdir()|os|刪除資料夾,但資料夾必須為空| 18 | |Path().unlink()|pathlib|刪除檔案| 19 | |removedirs()|os|遞迴刪除資料來,當子資料夾們成功刪除(資料夾必須為空),才會到其父資料們嘗試刪除| 20 | |glob()|glob|使用匹配的模式搭配remove()來刪除對應規則的檔案| 21 | |rmtree()|shutil|直接刪除整個非空的資料夾| 22 | 23 | 24 | ## 2. os.remove() 方法 25 | 26 | 27 | 28 | 29 | 30 | 1. **說明:**用以刪除指定路径的檔案 31 | 32 | 2. **可能報錯原因:** 33 | 34 | + 指定的檔案非檔案(像是資料夾)或根本不存在 35 | + 沒有權限刪除檔案 36 | 37 | 3. **舉例:** 刪除sample資料夾中的sample_file.txt,並使用try-except來捕捉刪除時遇到的錯誤 38 | 39 | 40 | 41 | 42 | 43 | 44 | ```Python 45 | import os 46 | 47 | path = 'sample/' 48 | 49 | file = 'sample/sample_file.txt' 50 | 51 | print('Sample Folder:', os.listdir(path)) 52 | 53 | try: 54 | 55 | os.remove(file) 56 | 57 | except OSError as e: 58 | 59 | print('Delete Problem: ', e) 60 | 61 | else: 62 | print('Delete File') 63 | print('Sample Folder: ', os.listdir(path)) 64 | ``` 65 | 66 | **執行結果** 67 | 68 | ``` 69 | Sample Folder: ['level1', 'not_null', 'python_file.py', 'sample.txt', 'sample_file.txt', 'sample_file1.txt', 'sample_file_example.txt', 'test_folder'] 70 | Delete File 71 | Sample Folder: ['level1', 'not_null', 'python_file.py', 'sample.txt', 'sample_file1.txt', 'sample_file_example.txt', 'test_folder'] 72 | ``` 73 | 74 | 75 | 76 | ## 3. os.unlink() 方法 77 | 78 | 79 | 80 | 1. **說明:** 用以刪除指定路徑的檔案 81 | 2. **舉例:** 刪除sample資料夾中的python_file.py 82 | 83 | 84 | ```Python 85 | import os 86 | 87 | path = 'sample/' 88 | 89 | 90 | print('Sample Folder: ', os.listdir(path)) 91 | 92 | os.unlink('sample/python_file.py') 93 | 94 | print('Delete File') 95 | print('Sample Folder: ', os.listdir(path)) 96 | ``` 97 | **執行結果** 98 | 99 | ``` 100 | Sample Folder: ['level1', 'not_null', 'python_file.py', 'sample.txt', 'sample_file1.txt', 'sample_file_example.txt', 'test_folder'] 101 | Delete File 102 | Sample Folder: ['level1', 'not_null', 'sample.txt', 'sample_file1.txt', 'sample_file_example.txt', 'test_folder'] 103 | ``` 104 | 105 | 106 | 107 | 108 | 109 | ## 4. rmdir() 方法 - 刪除空的資料夾 110 | 111 | 112 | 113 | 1. **說明:** 刪除資料夾,但資料夾必須為空 114 | 115 | 2. **舉例:** 刪除sample資料夾中的test_folder 116 | 117 | 118 | ```Python 119 | import os 120 | 121 | path = 'sample/' 122 | 123 | folder = 'sample/test_folder' 124 | print('Sample Folder:', os.listdir(path)) 125 | 126 | try: 127 | 128 | os. rmdir(folder) 129 | 130 | except OSError as e: 131 | 132 | print('Delete Problem: ', e) 133 | 134 | else: 135 | 136 | print('Delete File') 137 | print('Sample Folder: ', os. listdir(path)) 138 | ``` 139 | 140 | 141 | 142 | **執行結果** 143 | 144 | ``` 145 | Sample Folder: ['level1', 'not_null', 'sample.txt', 'sample_file1.txt', 'sample_file_example.txt', 'test_folder'] 146 | Delete File 147 | Sample Folder: ['level1', 'not_null', 'sample.txt', 'sample_file1.txt', 'sample_file_example.txt'] 148 | ``` 149 | 150 | 151 | 152 | 153 | 154 | ## 5. Pathlib 模組 - 刪除檔案 155 | 156 | 157 | 158 | 1. 說明: 用以刪除指定路徑的檔案 159 | 2. 舉例: 刪除sample資料夾中的sample_file.txt 160 | 161 | 162 | ```Python 163 | from pathlib import Path 164 | 165 | path = 'sample/' 166 | 167 | file = Path('sample/sample_file1.txt') 168 | 169 | print('Sample Folder: ', os.listdir(path)) 170 | 171 | try: 172 | 173 | file.unlink() 174 | print('Delete File') 175 | print('Sample Folder: ', os.listdir(path)) 176 | 177 | except OSError as e: 178 | print (f"Delete Problem: {e.strerror}") 179 | 180 | ``` 181 | 182 | **執行結果** 183 | 184 | ``` 185 | Sample Folder: ['level1', 'not_null', 'sample.txt', 'sample_file1.txt', 'sample_file_example.txt'] 186 | Delete File 187 | Sample Folder: ['level1', 'not_null', 'sample.txt', 'sample_file_example.txt'] 188 | ``` 189 | 190 | 191 | 192 | ## 6. removedirs() - 刪除資料夾 193 | 194 | 195 | 196 | 197 | 1. 說明: 遞迴刪除資料夾,當子資料夾們成功刪除(資料夾必須為空),才會到其父資料夾們嘗試刪除 198 | 2. 舉例: 我建立兩層資料夾(levell裡面包含level2),level2為空的資料夾,levell為只有装載level2的資料夾,我要將level1整個刪除 199 | 200 | 201 | ```Python 202 | import os 203 | 204 | path = 'sample/' 205 | folder = 'sample/level1/level2' 206 | 207 | print('Sample Folder: ', os.listdir(path)) 208 | 209 | try: 210 | 211 | os.removedirs (folder) 212 | 213 | except OSError as e: 214 | 215 | print('Delete Problem:', e) 216 | 217 | else: 218 | 219 | print('Delete File') 220 | print('Sample Folder: ', os.listdir(path)) 221 | ``` 222 | 223 | **執行結果** 224 | 225 | ``` 226 | Sample Folder: ['level1', 'not_null', 'sample.txt', 'sample_file_example.txt'] 227 | Delete File 228 | Sample Folder: ['not_null', 'sample.txt', 'sample_file_example.txt'] 229 | ``` 230 | 231 | 232 | 233 | 234 | 235 | ## 7. glob - 使用匹配模式來刪除檔案 236 | 237 | 238 | 239 | 1. 說明: 使用匹配的模式搭配remove()來刪除對應規則的檔案 240 | 241 | 2. 舉例: 刪除sample資料夾中所有以sample_為開頭的txt檔案 242 | 243 | 244 | ```Python 245 | import os 246 | 247 | import glob 248 | 249 | ## 刪除以sample_為開頭的txt檔案 250 | all_text = glob.glob('sample/sample_*.txt') 251 | 252 | path = 'sample/' 253 | 254 | print('Sample Folder: ', os.listdir(path)) 255 | 256 | for t in all_text: 257 | try: 258 | os.remove(t) 259 | 260 | except OSError as e: 261 | 262 | print('Delete Problem: ', e) 263 | 264 | print('Delete File') 265 | print('Sample Folder: ', os.listdir(path)) 266 | ``` 267 | 268 | **執行結果** 269 | 270 | ``` 271 | Sample Folder: ['not_null', 'sample.txt', 'sample_file_example.txt'] 272 | Delete File 273 | Sample Folder: ['not_null', 'sample.txt'] 274 | ``` 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | ## 8. rmtree() - 直接刪除整個非空的資料夾 283 | 284 | 285 | 286 | 舉例: 刪除整個not_null 資料夾 287 | 288 | 289 | ```Python 290 | import shutil 291 | 292 | path = 'sample/' 293 | 294 | folder = 'sample/not_null' 295 | 296 | print('Sample Folder: ', os.listdir(path)) 297 | 298 | try: 299 | 300 | shutil.rmtree (folder) 301 | 302 | except OSError as e: 303 | 304 | print('Delete Problem: ', e) 305 | 306 | else: 307 | 308 | print('Delete File') 309 | print('Sample Folder: ', os.listdir(path)) 310 | ``` 311 | **執行結果** 312 | 313 | ``` 314 | Sample Folder: ['not_null', 'sample.txt'] 315 | Delete File 316 | Sample Folder: ['sample.txt'] 317 | ``` 318 | 319 | 320 | 321 | 322 | 323 | 324 | -------------------------------------------------------------------------------- /delete-folder-file/delete_file_folder.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 12, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "Sample Folder: ['level1', 'not_null', 'python_file.py', 'sample.txt', 'sample_file.txt', 'sample_file1.txt', 'sample_file_example.txt', 'test_folder']\n", 13 | "Delete File\n", 14 | "Sample Folder: ['level1', 'not_null', 'python_file.py', 'sample.txt', 'sample_file1.txt', 'sample_file_example.txt', 'test_folder']\n" 15 | ] 16 | } 17 | ], 18 | "source": [ 19 | "import os\n", 20 | "\n", 21 | "path = 'sample/'\n", 22 | "\n", 23 | "file = 'sample/sample_file.txt'\n", 24 | "\n", 25 | "print('Sample Folder:', os.listdir(path))\n", 26 | "\n", 27 | "try:\n", 28 | "\n", 29 | " os.remove(file)\n", 30 | "\n", 31 | "except OSError as e:\n", 32 | "\n", 33 | " print('Delete Problem: ', e)\n", 34 | "\n", 35 | "else:\n", 36 | " print('Delete File')\n", 37 | " print('Sample Folder: ', os.listdir(path))" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": 13, 43 | "metadata": {}, 44 | "outputs": [ 45 | { 46 | "name": "stdout", 47 | "output_type": "stream", 48 | "text": [ 49 | "Sample Folder: ['level1', 'not_null', 'python_file.py', 'sample.txt', 'sample_file1.txt', 'sample_file_example.txt', 'test_folder']\n", 50 | "Delete File\n", 51 | "Sample Folder: ['level1', 'not_null', 'sample.txt', 'sample_file1.txt', 'sample_file_example.txt', 'test_folder']\n" 52 | ] 53 | } 54 | ], 55 | "source": [ 56 | "import os\n", 57 | "\n", 58 | "path = 'sample/'\n", 59 | "\n", 60 | "\n", 61 | "print('Sample Folder: ', os.listdir(path))\n", 62 | "\n", 63 | "os.unlink('sample/python_file.py')\n", 64 | "\n", 65 | "print('Delete File')\n", 66 | "print('Sample Folder: ', os.listdir(path))" 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": 14, 72 | "metadata": {}, 73 | "outputs": [ 74 | { 75 | "name": "stdout", 76 | "output_type": "stream", 77 | "text": [ 78 | "Sample Folder: ['level1', 'not_null', 'sample.txt', 'sample_file1.txt', 'sample_file_example.txt', 'test_folder']\n", 79 | "Delete File\n", 80 | "Sample Folder: ['level1', 'not_null', 'sample.txt', 'sample_file1.txt', 'sample_file_example.txt']\n" 81 | ] 82 | } 83 | ], 84 | "source": [ 85 | "import os\n", 86 | "\n", 87 | "path = 'sample/'\n", 88 | "\n", 89 | "folder = 'sample/test_folder'\n", 90 | "print('Sample Folder:', os.listdir(path))\n", 91 | "\n", 92 | "try:\n", 93 | "\n", 94 | " os. rmdir(folder)\n", 95 | "\n", 96 | "except OSError as e:\n", 97 | "\n", 98 | " print('Delete Problem: ', e)\n", 99 | "\n", 100 | "else:\n", 101 | "\n", 102 | " print('Delete File')\n", 103 | " print('Sample Folder: ', os. listdir(path))" 104 | ] 105 | }, 106 | { 107 | "cell_type": "code", 108 | "execution_count": 16, 109 | "metadata": {}, 110 | "outputs": [ 111 | { 112 | "name": "stdout", 113 | "output_type": "stream", 114 | "text": [ 115 | "Sample Folder: ['level1', 'not_null', 'sample.txt', 'sample_file1.txt', 'sample_file_example.txt']\n", 116 | "Delete File\n", 117 | "Sample Folder: ['level1', 'not_null', 'sample.txt', 'sample_file_example.txt']\n" 118 | ] 119 | } 120 | ], 121 | "source": [ 122 | "from pathlib import Path\n", 123 | "\n", 124 | "path = 'sample/'\n", 125 | "\n", 126 | "file = Path('sample/sample_file1.txt')\n", 127 | "\n", 128 | "print('Sample Folder: ', os.listdir(path))\n", 129 | "\n", 130 | "try:\n", 131 | "\n", 132 | " file.unlink()\n", 133 | " print('Delete File')\n", 134 | " print('Sample Folder: ', os.listdir(path))\n", 135 | "\n", 136 | "except OSError as e:\n", 137 | " print (f\"Delete Problem: {e.strerror}\")" 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": 21, 143 | "metadata": {}, 144 | "outputs": [ 145 | { 146 | "name": "stdout", 147 | "output_type": "stream", 148 | "text": [ 149 | "Sample Folder: ['level1', 'not_null', 'sample.txt', 'sample_file_example.txt']\n", 150 | "Delete File\n", 151 | "Sample Folder: ['not_null', 'sample.txt', 'sample_file_example.txt']\n" 152 | ] 153 | } 154 | ], 155 | "source": [ 156 | "import os\n", 157 | "\n", 158 | "path = 'sample/'\n", 159 | "folder = 'sample/level1/level2'\n", 160 | "\n", 161 | "print('Sample Folder: ', os.listdir(path))\n", 162 | "\n", 163 | "try:\n", 164 | "\n", 165 | " os.removedirs (folder)\n", 166 | "\n", 167 | "except OSError as e:\n", 168 | "\n", 169 | " print('Delete Problem:', e)\n", 170 | "\n", 171 | "else:\n", 172 | "\n", 173 | " print('Delete File')\n", 174 | " print('Sample Folder: ', os.listdir(path))" 175 | ] 176 | }, 177 | { 178 | "cell_type": "code", 179 | "execution_count": 24, 180 | "metadata": {}, 181 | "outputs": [ 182 | { 183 | "name": "stdout", 184 | "output_type": "stream", 185 | "text": [ 186 | "Sample Folder: ['not_null', 'sample.txt', 'sample_file_example.txt']\n", 187 | "Delete File\n", 188 | "Sample Folder: ['not_null', 'sample.txt']\n" 189 | ] 190 | } 191 | ], 192 | "source": [ 193 | "import os\n", 194 | "\n", 195 | "import glob\n", 196 | "\n", 197 | "## 刪除以sample_為開頭的txt檔案\n", 198 | "all_text = glob.glob('sample/sample_*.txt')\n", 199 | "\n", 200 | "path = 'sample/'\n", 201 | "\n", 202 | "print('Sample Folder: ', os.listdir(path))\n", 203 | "\n", 204 | "for t in all_text:\n", 205 | " try:\n", 206 | " os.remove(t)\n", 207 | "\n", 208 | " except OSError as e:\n", 209 | "\n", 210 | " print('Delete Problem: ', e)\n", 211 | "\n", 212 | "print('Delete File')\n", 213 | "print('Sample Folder: ', os.listdir(path))" 214 | ] 215 | }, 216 | { 217 | "cell_type": "code", 218 | "execution_count": 28, 219 | "metadata": {}, 220 | "outputs": [ 221 | { 222 | "name": "stdout", 223 | "output_type": "stream", 224 | "text": [ 225 | "Sample Folder: ['not_null', 'sample.txt']\n", 226 | "Delete File\n", 227 | "Sample Folder: ['sample.txt']\n" 228 | ] 229 | } 230 | ], 231 | "source": [ 232 | "import shutil\n", 233 | "\n", 234 | "path = 'sample/'\n", 235 | "\n", 236 | "folder = 'sample/not_null'\n", 237 | "\n", 238 | "print('Sample Folder: ', os.listdir(path))\n", 239 | "\n", 240 | "try:\n", 241 | "\n", 242 | " shutil.rmtree (folder)\n", 243 | "\n", 244 | "except OSError as e:\n", 245 | "\n", 246 | " print('Delete Problem: ', e)\n", 247 | "\n", 248 | "else:\n", 249 | "\n", 250 | " print('Delete File')\n", 251 | " print('Sample Folder: ', os.listdir(path))" 252 | ] 253 | } 254 | ], 255 | "metadata": { 256 | "kernelspec": { 257 | "display_name": "Python 3", 258 | "language": "python", 259 | "name": "python3" 260 | }, 261 | "language_info": { 262 | "codemirror_mode": { 263 | "name": "ipython", 264 | "version": 3 265 | }, 266 | "file_extension": ".py", 267 | "mimetype": "text/x-python", 268 | "name": "python", 269 | "nbconvert_exporter": "python", 270 | "pygments_lexer": "ipython3", 271 | "version": "3.7.6" 272 | } 273 | }, 274 | "nbformat": 4, 275 | "nbformat_minor": 4 276 | } 277 | -------------------------------------------------------------------------------- /delete-folder-file/images/1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/delete-folder-file/images/1.PNG -------------------------------------------------------------------------------- /delete-folder-file/sample/not_null/python_file.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/delete-folder-file/sample/not_null/python_file.py -------------------------------------------------------------------------------- /delete-folder-file/sample/not_null/sample.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/delete-folder-file/sample/not_null/sample.txt -------------------------------------------------------------------------------- /delete-folder-file/sample/not_null/sample_file.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/delete-folder-file/sample/not_null/sample_file.txt -------------------------------------------------------------------------------- /delete-folder-file/sample/not_null/sample_file1.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/delete-folder-file/sample/not_null/sample_file1.txt -------------------------------------------------------------------------------- /delete-folder-file/sample/not_null/sample_file_example.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/delete-folder-file/sample/not_null/sample_file_example.txt -------------------------------------------------------------------------------- /delete-folder-file/sample/python_file.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/delete-folder-file/sample/python_file.py -------------------------------------------------------------------------------- /delete-folder-file/sample/sample.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/delete-folder-file/sample/sample.txt -------------------------------------------------------------------------------- /delete-folder-file/sample/sample_file.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/delete-folder-file/sample/sample_file.txt -------------------------------------------------------------------------------- /delete-folder-file/sample/sample_file1.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/delete-folder-file/sample/sample_file1.txt -------------------------------------------------------------------------------- /delete-folder-file/sample/sample_file_example.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/delete-folder-file/sample/sample_file_example.txt -------------------------------------------------------------------------------- /eval/.ipynb_checkpoints/eval-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 4 6 | } 7 | -------------------------------------------------------------------------------- /eval/eval.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 4, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "name": "stdout", 10 | "output_type": "stream", 11 | "text": [ 12 | "\n", 13 | "(23+6-9)*8\n", 14 | "------------ eval() ---------------\n", 15 | "\n", 16 | "160\n" 17 | ] 18 | } 19 | ], 20 | "source": [ 21 | "x = '(23+6-9)*8'\n", 22 | "print(type(x))\n", 23 | "print(x)\n", 24 | "## eval\n", 25 | "print('------------ eval() ---------------')\n", 26 | "\n", 27 | "print(type(eval(x)))\n", 28 | "print(eval(x))" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": 7, 34 | "metadata": {}, 35 | "outputs": [ 36 | { 37 | "name": "stdout", 38 | "output_type": "stream", 39 | "text": [ 40 | "Give a number:6\n", 41 | "plus 2\n" 42 | ] 43 | }, 44 | { 45 | "data": { 46 | "text/plain": [ 47 | "8" 48 | ] 49 | }, 50 | "execution_count": 7, 51 | "metadata": {}, 52 | "output_type": "execute_result" 53 | } 54 | ], 55 | "source": [ 56 | "x = int(input('Give a number:'))\n", 57 | "print('plus 2')\n", 58 | "eval('x + 2')" 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": 12, 64 | "metadata": {}, 65 | "outputs": [ 66 | { 67 | "name": "stdout", 68 | "output_type": "stream", 69 | "text": [ 70 | "\n", 71 | "--------------eval------------------\n", 72 | "\n", 73 | "{'Student': 'A', 'Score': 99}\n" 74 | ] 75 | } 76 | ], 77 | "source": [ 78 | "x=\"{'Student': 'A', 'Score': 99}\"\n", 79 | "print(type(x))\n", 80 | "\n", 81 | "print('--------------eval------------------')\n", 82 | "print(type(eval(x)))\n", 83 | "print(eval(x))" 84 | ] 85 | }, 86 | { 87 | "cell_type": "code", 88 | "execution_count": 17, 89 | "metadata": {}, 90 | "outputs": [ 91 | { 92 | "name": "stdout", 93 | "output_type": "stream", 94 | "text": [ 95 | "8\n", 96 | "{'Student': 'Ken', 'Score': 99}\n" 97 | ] 98 | } 99 | ], 100 | "source": [ 101 | "## 全局變量 globals 應用\n", 102 | "print(eval('x + 2', {'x': 6}))\n", 103 | "print(eval(\"{'Student': 'Ken', 'Score': score}\", {'score': 99}))" 104 | ] 105 | }, 106 | { 107 | "cell_type": "code", 108 | "execution_count": 44, 109 | "metadata": {}, 110 | "outputs": [ 111 | { 112 | "name": "stdout", 113 | "output_type": "stream", 114 | "text": [ 115 | "10\n", 116 | "{'Student': 'Ken', 'Score': 60}\n", 117 | "{'Student': 'Allen', 'score': 99}\n" 118 | ] 119 | } 120 | ], 121 | "source": [ 122 | "## locals 和 globals 都給定字典\n", 123 | "print(eval('x + 2',{'x': 6},{'x':8}))\n", 124 | "print(eval(\"{'Student':'Ken','Score': score}\", {'score': 99}, {'score': 60}))\n", 125 | "\n", 126 | "## 使用locals()來獲取局部命名空間的字典,並同時取全局與局部的值,只要不同就能同時使用\n", 127 | "name = \"Allen\"\n", 128 | "print(eval(\"{'Student': name, 'score': score}\", {'score': 99}, locals()))" 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": 12, 134 | "metadata": {}, 135 | "outputs": [ 136 | { 137 | "name": "stdout", 138 | "output_type": "stream", 139 | "text": [ 140 | "输入格:__import__('os').system('dir') \n" 141 | ] 142 | }, 143 | { 144 | "data": { 145 | "text/plain": [ 146 | "0" 147 | ] 148 | }, 149 | "execution_count": 12, 150 | "metadata": {}, 151 | "output_type": "execute_result" 152 | } 153 | ], 154 | "source": [ 155 | "t = input(\"输入格:\")\n", 156 | "eval(t)" 157 | ] 158 | } 159 | ], 160 | "metadata": { 161 | "kernelspec": { 162 | "display_name": "Python 3", 163 | "language": "python", 164 | "name": "python3" 165 | }, 166 | "language_info": { 167 | "codemirror_mode": { 168 | "name": "ipython", 169 | "version": 3 170 | }, 171 | "file_extension": ".py", 172 | "mimetype": "text/x-python", 173 | "name": "python", 174 | "nbconvert_exporter": "python", 175 | "pygments_lexer": "ipython3", 176 | "version": "3.7.6" 177 | } 178 | }, 179 | "nbformat": 4, 180 | "nbformat_minor": 4 181 | } 182 | -------------------------------------------------------------------------------- /eval/eval.md: -------------------------------------------------------------------------------- 1 | # 給自己的Python小筆記 - 如何將字符串中的語句 轉換成可以執行的Python命令? - eval() 函數使 用教學 2 | 3 | 4 | 5 | YoYo~~不知道大家有沒有遇到過要執行的Python語句包覆在字符串裡面,也就是這條語句是字符串類型,但是我們又需要去執行這裡面的Python程式,而不是只是執行一個字符串,這時候就會需要用到eval()這個魔法了XD 6 | 7 | 8 | 9 | 10 | 11 | ## 1. eval() 函數與參數介紹 12 | 13 | 14 | 15 | + 函數 16 | ``` 17 | eval(source, globals=None, locals=None, /) 18 | ``` 19 | + 參數介紹 20 | 21 | 1. source: 傳人 Python表達式的字符串或是compile()傳回的程式碼物件 22 | 23 | 2. globals(): 為一個可選參數,是全局命名的空間,如果使用的話,就一定要是一個字典形式 24 | 25 | 3. locals(): 為一個可選參數,是局部命名的空間,如果使用的話(不為None),可以是任何的映射(mapping) 26 | 27 | **提醒:** 如果只有給定globals,則locals預設就為全局變量 28 | 29 | **補充:** 如果不瞭解命名空間的朋友們,可以參考一下這篇:https://www.runoob.com/python3/python3-namespace-scope.html,我覺得寫得很詳細喔 30 | 31 | **觀念: Python用globals()來記錄全局變數,而用locals()來記錄局部變數,而這些變數都是以字典的格式存在這兩個命名空間中** 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | ## 2. 實作 42 | 43 | 44 | 45 | ### a. 數值運算 46 | ```Python 47 | x = '(23+6-9)*8' 48 | print(type(x)) 49 | print(x) 50 | ## eval 51 | print('------------ eval() ---------------') 52 | 53 | print(type(eval(x))) 54 | print(eval(x)) 55 | ``` 56 | **執行結果** 57 | 58 | ``` 59 | 60 | (23+6-9)*8 61 | ------------ eval() --------------- 62 | 63 | 160 64 | ``` 65 | 66 | 67 | 68 | 69 | 70 | ### b. 變數使用 71 | ```Python 72 | x = int(input('Give a number:')) 73 | print('plus 2') 74 | eval('x + 2') 75 | ``` 76 | **執行結果** 77 | 78 | ``` 79 | Give a number:6 80 | plus 2 81 | ``` 82 | 83 | Out[7]: 84 | 85 | ``` 86 | 8 87 | ``` 88 | 89 | 90 | 91 | 92 | 93 | ### c. 字典轉換 94 | ```Python 95 | x="{'Student': 'A', 'Score': 99}" 96 | print(type(x)) 97 | 98 | print('--------------eval------------------') 99 | print(type(eval(x))) 100 | print(eval(x)) 101 | ``` 102 | **執行結果** 103 | 104 | ``` 105 | 106 | --------------eval------------------ 107 | 108 | {'Student': 'A', 'Score': 99} 109 | ``` 110 | 111 | 112 | 113 | 114 | 115 | ### d. globals locals 116 | 117 | + globals() 應用: 將score變量帶入 118 | 119 | 120 | ```Python 121 | ## 全局變量 globals 應用 122 | print(eval('x + 2', {'x': 6})) 123 | print(eval("{'Student': 'Ken', 'Score': score}", {'score': 99})) 124 | ``` 125 | 126 | **執行結果** 127 | 128 | ``` 129 | 8 130 | {'Student': 'Ken', 'Score': 99} 131 | ``` 132 | 133 | 134 | 135 | 136 | + 當globals 和 locals 同時給的時候 137 | ```Python 138 | ## locals 和 globals 都給定字典 139 | print(eval('x + 2',{'x': 6},{'x':8})) 140 | print(eval("{'Student':'Ken','Score': score}", {'score': 99}, {'score': 60})) 141 | 142 | ## 使用locals()來獲取局部命名空間的字典,並同時取全局與局部的值,只要不同就能同時使用 143 | name = "Allen" 144 | print(eval("{'Student': name, 'score': score}", {'score': 99}, locals())) 145 | ``` 146 | 147 | **執行結果** 148 | 149 | ``` 150 | 10 151 | {'Student': 'Ken', 'Score': 60} 152 | {'Student': 'Allen', 'score': 99} 153 | ``` 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | **結果:會以locals的變數來決定** 162 | 163 | **筆記: 同時取全局與局部的值,只要不同就能同時使用** 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | ## 3. 安全性 172 | 173 | 174 | 175 | **狀況:** 當程式中有input()這個的函式,讓使用者可以輸入語句到程式時 176 | 177 | input()會將使用者輸入的語句轉換成字符串,而此時如果又用eval()轉換成Python程式語句時,可能就存在危險性,像是如下,使用者可以透過一些Python語句來獲取電腦的資訊 178 | 179 | 180 | 181 | 182 | 183 | 輸入: 184 | 185 | 1. `__import__('os').system('dir')` 獲取資料夾目錄 186 | 187 | 2. `__import__('os').system('id')` 獲取電腦使用者的ID與群組ID 188 | 189 | ```Python 190 | t = input('输入格:') 191 | eval(t) 192 | ``` 193 | 194 | 195 | 196 | **執行例子** 197 | 198 | ``` 199 | 输入格:__import__('os').system('dir') 200 | ``` 201 | 202 | Out[12]: 203 | 204 | ``` 205 | 0 206 | ``` 207 | 208 | 只要使用os這個模組就能輕鬆獲取電腦的一些資訊,所以使用上要特別注意這個問題 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | -------------------------------------------------------------------------------- /excel_operation/read_csv/給自己的Python小筆記 - 導入CSV檔 - pandas.read_csv()參數說明.md: -------------------------------------------------------------------------------- 1 | # 給自己的Python小筆記 - 導入CSV檔 - pandas.read_csv()參數說明 2 | 3 | 4 | 5 | 6 | 7 | YoYo,今天來介紹另一種使用Pandas來讀取Excel檔的方法,但這次不同的地方是Excel檔的副檔名需要為CSV檔喔,而我們要使用的是pandas.read_csv()這個方法,由於上一篇介紹過的pandas.read_excel()與這次要分享的方法,在很多參數上是相仿的,所以我這篇就不實作囉,大家可以根據這篇的參數說明自己試試看 8 | 9 | 10 | 11 | 12 | 13 | ## read_csv() & read_excel() 都是導入Excel檔,並轉換成Python可操作的DataFrame格式,那它們最大的差別是什麼? 14 | 15 | 16 | 17 | 答案非常簡單,除了參數的差別,它們使用上的不同在,雖然都是導入Excel檔,但是所導入的Excel檔格式並不相同喔,有些Excel檔需要read_csv()來導入,有些則需要read_excel來導入喔 18 | 19 | 20 | 21 | 22 | 23 | ## pandas.read_csv()所有的參數 24 | 25 | 26 | 27 | **利用Python查詢pandas.read_csv()所有參數與說明** 28 | 29 | ```Python 30 | import pandas as pd 31 | 32 | help(pd.read_csv) 33 | ``` 34 | 35 | 36 | 37 | **所有參數** 38 | 39 | ``` 40 | read_csv(filepath_or_buffer: Union[str, pathlib.Path, IO[~AnyStr]], sep=',', delimiter=None, header='infer', names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, cache_dates=True, iterator=False, chunksize=None, compression='infer', thousands=None, decimal: str = '.', lineterminator=None, quotechar='"', quoting=0, doublequote=True, escapechar=None, comment=None, encoding=None, dialect=None, error_bad_lines=True, warn_bad_lines=True, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None) 41 | ``` 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | ## 參數介紹 50 | 51 | 52 | 53 | #### 常使用到的參數 54 | 55 | 56 | 57 | 58 | 59 | | **參數** | **傳入參數的值** | **說明** | 60 | | ------------------ | ---------------------------------------------------------- | ------------------------------------------------------------ | 61 | | filepath_or_buffer | str, path, object or file-like object | 指定檔案路徑,也可以是URL字串(有效的URL包含 http, ftp, s3 位址,或是擁有read()方法的物件,像是open file或StringIO物件) | 62 | | sep | str, default ',' | 指定分隔符,預設為',',也就是用逗號分隔,分隔符需要長於一個字符,並且不能是'\s+',可以使用的分隔符有像是正則表達式的方式:"\r\t"等等 | 63 | | delimiter | str, default None | 定界符,為備選的分隔符,如果有指定這個參數,sep參數就會失效 | 64 | | delim_whitespace | bool, default False | 指定空格(' ' or '\t' )是否會用於定界符(delimiter),它等同於sep = '\s+'的效果,如果有指定這個參數,delimiter參數就會失效 | 65 | | header | int, list of int, default 'infer': | 指定數據中哪一列為列名,如果傳入1,代表指定第二列為列名,以此類推,預設為0,也就是指定第一列為列名,而傳入[0,1,2]就是將第一、二、三列都當成是列名,傳入None,表示不使用任何數據裡的列當成是列名 | 66 | | names | array-like, optional | 指定一個自定義的列名,傳入一個串列,裡面裝自定義的名稱,但要注意數量要與原數據的列同數量 | 67 | | index_col | int, str, sequence of int / str, or False, default None | 指定哪一列為索引列,傳入整數來指定哪一列來成為索引列,傳入串列,裝多個整數,來指定哪些列為索引列,預設為None,代表它會自動創建以0開始的列,來當索引列 | 68 | | usecols | list-like or callable, optional | 指定讀取Excel檔中的哪些列,傳入串列(list)來指定要解析導入哪些列,傳入字串(str)用Excel檔中的序列字母來指定要導入哪些列,使用":"來代表字母序號的範圍,","代表咬指定哪些列,像是"A:E",代表解析導入A到E列,而"A, C, E:F",代表解析導入A、C和E到F列,預設值為None,代表解析導入所有列 | 69 | | squeeze | bool, default False | 當解析導入的只有一列時,會轉成Series格式 | 70 | | prefix | str, optional | 在header = None沒有指定列名的時候,給列添加前綴,header為None時,會自動生成0,1,2,3,4...的列名,這時加上prefix = 'A',就會產生新的列名為A1, A2, A3, A4... | 71 | | mangle_dupe_cols | bool, default True | 預設為True,代表當有重複出現的列名時,像是'A'...'A',將列名替換成'A', 'A.1', 'A.2'...'A.N',如果傳入False,就會將重複名稱的列名覆蓋掉 | 72 | | nrows | int, optional | 指定欲讀取前幾行 | 73 | | na_values | scaler, str, list-like, or dict, optional | 將指定的數據欄位字串值,改為NaN | 74 | | skip_blank_lines | bool, default True | 當設置為True時,會跳過所有值為空值的行,而不是填入NaN,然後解析導入 | 75 | | dtype | Type name or dict of column -> type, optional | 改變原數據類型,預設為None,表示不改變原數據類型,像是dtype = {2: 'float64', 3:'float64', 4:'float64'},代表會將第三、四、五列的數據類型改為浮點數類型 | 76 | 77 | 78 | 79 | **這篇我想當成是大家在導入CSV檔時候,不用記得所有參數,需要用到的時候,再來看看的小筆記,所以有些可能比較不常用到的參數,我這邊就不做介紹囉,有興趣的大家可以直接參考官網([https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-read-csv-table)喔](https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html?fbclid=IwAR3eZWtkbclFCO_xlCPZmfnYH2XE0Zkfe90_dbNdHTYLEbQCJUuyCseBQhc#io-read-csv-table)喔)** 80 | 81 | 82 | 83 | 84 | 85 | **想知道更多使用Pandas導入不同檔案類型的方法,也可以參考官網這頁([https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-read-csv-table)喔**](https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html?fbclid=IwAR321Nzr1ADFuL8hNKoSkDF2azeikNPk8qFSfOqLAzzlTLk8bzggolVs8pE#io-read-csv-table)喔) 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | ## Reference 96 | 97 | 98 | 99 | [https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-read-csv-table](https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html?fbclid=IwAR1xv1mbDqEk0GyAn2ksSUo-UxWCJ5KOutNASm_8DgsvjwIXJT6GRjTf-5k#io-read-csv-table) 100 | 101 | [https://blog.csdn.net/zhangjianjaEE/article/details/78543743](https://blog.csdn.net/zhangjianjaEE/article/details/78543743?fbclid=IwAR2fvTmFPMIOBCmxJPGztpreWtqLtBhhuAZlY-WUBXqamMd5KXld4TMd8_A) -------------------------------------------------------------------------------- /excel_operation/read_excel/data/dataset_example.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/data/dataset_example.xlsx -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image1.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image10.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image10.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image11.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image11.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image12.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image12.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image13.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image13.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image14.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image14.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image15.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image15.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image16.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image16.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image17.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image17.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image18.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image18.png -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image19.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image19.png -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image2.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image2.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image20.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image20.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image21.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image21.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image23.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image23.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image28.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image28.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image3.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image3.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image4.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image4.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image5.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image5.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image6.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image6.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image7.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image7.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image8.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image8.PNG -------------------------------------------------------------------------------- /excel_operation/read_excel/images/image9.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/excel_operation/read_excel/images/image9.PNG -------------------------------------------------------------------------------- /interpolate/.ipynb_checkpoints/interpolate-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 4 6 | } 7 | -------------------------------------------------------------------------------- /interpolate/images/1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/interpolate/images/1.PNG -------------------------------------------------------------------------------- /interpolate/images/2.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/interpolate/images/2.PNG -------------------------------------------------------------------------------- /interpolate/images/3.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/interpolate/images/3.PNG -------------------------------------------------------------------------------- /interpolate/images/4.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/interpolate/images/4.PNG -------------------------------------------------------------------------------- /interpolate/images/5.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/interpolate/images/5.PNG -------------------------------------------------------------------------------- /interpolate/images/6.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/interpolate/images/6.PNG -------------------------------------------------------------------------------- /interpolate/images/7.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/interpolate/images/7.PNG -------------------------------------------------------------------------------- /interpolate/images/8.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/interpolate/images/8.PNG -------------------------------------------------------------------------------- /interpolate/interpolate-method.md: -------------------------------------------------------------------------------- 1 | # 給自己的Python筆記-功能強大的缺失值處理方 法- DataFrame中的缺失值如何使用插值的方法來填充 - pandas.DataFrame.interpolate() 使用筆記 2 | 3 | 4 | 5 | 6 | 7 | Hi Hi, 在之前的文章中(Machine Learning -給自己的機器學習筆記 - 被數據集中空空的慢位嚇到了嗎 - 數據集中的缺失值如何處理?), 有跟大家介紹過如何使用各種方法來填補缺失值, 而這篇我想跟大家介招一個功能非常些的方法 - 插值, 來填補這些缺失值 8 | 9 | 10 | 11 | 12 | 13 | ## 1.插值方法? 14 | 15 | 16 | 17 | + **說明**: 插值又稱為內插, 為一種透過已知的離散數據點, 在範圍內推算出新的數據點的方法 18 | 19 | + **用法**: 透過計算函數在已知點的取值狀況, 估算出函數在其它點處的近似值, 這樣就能用已知的數據來估算出那些未知的數據 20 | 21 | + **與機器學習擬和的不同**: 插值法計算出的函數所繪出的擬和曲線通過所有已知點 22 | 23 | 24 | 25 | 26 | 27 | ## 2. DataFrame.interpolate() 參數介紹 28 | 29 | 函數 30 | ``` 31 | interpolate (self, method='linear', axis=0, limit=None, inplace=False, limit_direction='forward', limit_area=None, downcast-None, **kwargs) 32 | ``` 33 | 34 | 35 | 參數 36 | 37 | 1. method:使用的插值技術, 預設為"linear' ,可用選項: 38 | 39 | + 'linear': 忽略索引, 並將值等距的對待,是Mulitilndex(多重索引)唯一支持的方法 40 | 41 | + 'time': 處理每日和更高分辨率的數據, 以給定的時間間隔長度來進行插值 42 | 43 | + 'index'、'values': 使用索引的實際數值 44 | 45 | + 'pad': 使用現有值填寫NaN 46 | 47 | + 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'spline', 'barycentric', 'polynomial': 傳遞給scipy.interpolate.interpld,這些方法使用數值的索引值,'polynomial'和'spline都要求您還可以指定一個order (int),例如df.interpolate (method ='polynomial order = 5) 48 | 49 | + 'krogh', 'piecewise_polynomial', 'spline', pchip', akima': 包裝圍繞類似的SciPy插值方法名稱 50 | 51 | + 'from_derivatives': 指scipy.interpolate.Bpoly.from_derivatives取代了" piecewise_polynomial"插值方法 52 | 53 | 54 | 2. axis:沿軸進行內插,1:沿列,0:沿行,預設為None 55 | 56 | 3. limit: 進行插值的最大連續NaN數,一定要大於0 57 | 58 | 4. inplace: 傳入True/False,預設為False,如果設定True,就會盡可能的更新數據 59 | 60 | 61 | 5. limit_direction: 選項有'forward', 'backward', 'both',預設為"forward",如果設定limit 就會依照這邊設定的方向填充連續的NaN 62 | 63 | 6. limit_area: 選項有None, 'inside', 'outside',預設為None,當設定limit時,對插值的限制 64 | 65 | 66 | + None: 沒有填充限制 67 | + 'inside': 僅填補有效值(interpolate)包圍的NaN 68 | + 'outside': 僅在有效值以外(extrapolate)填充NaN 69 | 70 | 7. downcast: 選項有'infer'或None,None是預設,如果可能,請向下轉换dtypes 71 | 72 | 8. **kwargs:關鍵字參數傳遞給插值函數 73 | 74 | 75 | 76 | 77 | 78 | ## 實作 79 | 80 | 81 | 82 | ### 1. 基本插補 -將所有NaN進行内插 83 | 84 | 85 | 86 | 87 | ```Python 88 | import pandas as pd 89 | import numpy as np 90 | 91 | ## 創建數據集 92 | df = pd. DataFrame({ 93 | 'A': [2, 6, None, 8, 10], 94 | 'B': [6, np.nan, 2, None ,8] 95 | }) 96 | print('original Dataset: ') 97 | print(df) 98 | 99 | 100 | ## 進行插值 101 | interpolate_df = df.interpolate() 102 | print('Interpolated Dataset: ') 103 | interpolate_df 104 | ``` 105 | **執行結果** 106 | 107 | ![1](images\1.PNG) 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | ### 2. 使用Method函數來指定內插的方法 116 | 117 | 118 | 119 | + 這邊以pad('pad': 使用現有值填寫NaN)方法來實作 120 | 121 | 122 | 123 | ```Python 124 | import pandas as pd 125 | import numpy as np 126 | 127 | ## 創建數據集 128 | df = pd. DataFrame({ 129 | 'A': [2, 6, None, 8, 10], 130 | 'B': [6, np.nan, 2, None ,8] 131 | }) 132 | print('original Dataset: ') 133 | print(df) 134 | 135 | 136 | ## 進行插值 137 | interpolate_df = df.interpolate(method = 'pad') 138 | print('Interpolated Dataset: ') 139 | interpolate_df 140 | ``` 141 | **執行結果** 142 | 143 | ![2](images\2.PNG) 144 | 145 | + 這邊以Polynomial方法來實作 - 使用二階多項式的插值方法 146 | 147 | order = 2 為Polynomial方法(函數)的關鍵字引數(參數) 148 | 149 | 150 | ```Python 151 | import pandas as pd 152 | import numpy as np 153 | 154 | ## 創建數據集 155 | df = pd. DataFrame({ 156 | 'A': [2, 6, None, 8, 10], 157 | 'B': [6, np.nan, 2, None ,8] 158 | }) 159 | print('original Dataset: ') 160 | print(df) 161 | 162 | 163 | ## 進行插值 164 | interpolate_df = df.interpolate(method = 'polynomial', order = 2) 165 | print('Interpolated Dataset: ') 166 | interpolate_df 167 | ``` 168 | **執行結果** 169 | 170 | ![3](images\3.PNG) 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | ### 3. 使用limit參數來限制填補的最大連續數量 179 | 180 | ```Python 181 | import pandas as pd 182 | import numpy as np 183 | 184 | ## 創建數據集 185 | df = pd. DataFrame({ 186 | 'A': [2, 6, None, 8, 10], 187 | 'B': [6, np.nan, np.nan, None ,8] 188 | }) 189 | print('original Dataset: ') 190 | print(df) 191 | 192 | 193 | ## 進行插值 194 | interpolate_df = df.interpolate(limit = 1) 195 | print('Interpolated Dataset: ') 196 | interpolate_df 197 | ``` 198 | **執行結果** 199 | 200 | ![4](images\4.PNG) 201 | 202 | 203 | 204 | 205 | 206 | ### 4. 根據哪個方向進行最大的連續填補數量 - limit_direction 207 | 208 | 209 | 210 | + 從後面開始內插 211 | 212 | ```Python 213 | import pandas as pd 214 | import numpy as np 215 | 216 | ## 創建數據集 217 | df = pd. DataFrame({ 218 | 'A': [2, 6, None, 8, 10], 219 | 'B': [6, np.nan, np.nan, None ,8] 220 | }) 221 | print('original Dataset: ') 222 | print(df) 223 | 224 | 225 | ## 進行插值 226 | interpolate_df = df.interpolate(limit_direction = 'backward', limit = 1) 227 | print('Interpolated Dataset: ') 228 | interpolate_df 229 | ``` 230 | **執行結果** 231 | 232 | ![5](images\5.PNG) 233 | 234 | 235 | 236 | 237 | 238 | 239 | + 從兩邊的中間位置開始進行內插 240 | 241 | ```Python 242 | import pandas as pd 243 | import numpy as np 244 | 245 | ## 創建數據集 246 | df = pd. DataFrame({ 247 | 'A': [2, 6, None, 8, 10], 248 | 'B': [6, np.nan, np.nan, None ,8] 249 | }) 250 | print('original Dataset: ') 251 | print(df) 252 | 253 | 254 | ## 進行插值 255 | interpolate_df = df.interpolate(limit_direction = 'both', limit = 1) 256 | print('Interpolated Dataset: ') 257 | interpolate_df 258 | ``` 259 | **執行結果** 260 | 261 | ![6](images\6.PNG) 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | ### 5. 沿著行或列進行內插 - axis 272 | 273 | 274 | ```Python 275 | import pandas as pd 276 | import numpy as np 277 | 278 | ## 創建數據集 279 | df = pd. DataFrame({ 280 | 'A': [2, 6, None, 8, 10], 281 | 'B': [6, np.nan, np.nan, None ,8] 282 | }) 283 | print('original Dataset: ') 284 | print(df) 285 | 286 | 287 | ## 進行插值 288 | interpolate_df = df.interpolate(axis = 1) 289 | print('Interpolated Dataset: ') 290 | interpolate_df 291 | ``` 292 | **執行結果** 293 | 294 | ![7](images\7.PNG) 295 | 296 | 297 | 298 | ### 6. 對時間序列型(Time-Series)的數據集進行內插 299 | 300 | 301 | 302 | **注意**: 當我們要使用inplace參數時,因為它會盡可能的更新數據集,所以只要使用df.interpolate(inplace = True),不用再寫成interpolate_df = df.interpolate(inplace = True),不然會顯示不出資料 303 | 304 | 305 | 306 | 307 | ```Python 308 | import pandas as pd 309 | import numpy as np 310 | 311 | ## 創建數據集 312 | time = ['Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun'] 313 | score = [28, 52, np.nan, 60, 66, 98, 100] 314 | df = pd.DataFrame({ 'time': time, 'score': score}) 315 | print('Original Dataset: ') 316 | print(df) 317 | ## 進行插補 318 | df.interpolate(inplace = True) 319 | print('Interpolated Dataset: ') 320 | df 321 | ``` 322 | 323 | **執行結果** 324 | 325 | ![8](images\8.PNG) -------------------------------------------------------------------------------- /matplotlib/concept/[程式觀念] 大家都會使用plt畫圖,但是你真的知道plt ax fig是什麼嗎怎麼用.md: -------------------------------------------------------------------------------- 1 | # [程式觀念] 大家都會使用plt畫圖,但是你真的知道plt / ax / fig是什麼嗎?怎麼用? 2 | 3 | 4 | 5 | 嗨嗨,今天一如往常,上班遇到困難馬上google,但在無意間查詢別的資訊時,看到一篇非常非常有趣的文章(我會在下面的參考文章附上喔),過去我在畫視覺化圖時,也都是使用plt.xxx,然後要什麼功能就馬上google,接著就是貼上,每次寫的視覺化程式都不太一樣xd,心裡只是想反正可以work就好,這篇文章完全打中了我xd,作者一開始也是這樣,但他決定好好搞明白並分享給大家,而我也決定在跪著看完這篇文章後,分享給大家,我所學習到觀念 6 | 7 | 8 | 9 | 10 | 11 | ## 1. 動機 12 | 13 | 14 | 15 | 每次我在要畫視覺畫圖時,總是去google上找尋別人的code,然後就來個複製,修改成我要的後就貼上了,要什麼功能再繼續google,但是我也遇到一樣的疑惑,就是很常會發現有些看似不同的方法卻達到了一樣的效果,而隨著每次查詢資料的不同,都來個很不一樣的code,但明明可能根本就是一樣的功能,像是作者提到如果要設定標題名稱有以下兩種寫法,那我到底應該要用哪種方法? 16 | 17 | 18 | 19 | ```Python 20 | plt.title() 21 | ax.set_title() 22 | ``` 23 | 24 | 25 | 26 | 舉例: 27 | 28 | ```Pythonimport matplotlib.pyplot as plt 29 | import matplotlib.pyplot as plt 30 | 31 | x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 32 | y = [66, 28, 32, 58, 18, 2, 99, 77, 66, 58] 33 | 34 | fig, ax = plt.subplots() 35 | 36 | plt.plot(x, y) 37 | plt.title('Title Method 1') 38 | 39 | plt.show() 40 | ``` 41 | 42 | ![image3](images\image3.PNG) 43 | 44 | 45 | 46 | ```Python 47 | import matplotlib.pyplot as plt 48 | 49 | x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 50 | y = [66, 28, 32, 58, 18, 2, 99, 77, 66, 58] 51 | 52 | fig, ax = plt.subplots() 53 | 54 | plt.plot(x, y) 55 | ax.set_title('Title Method 2') 56 | 57 | plt.show() 58 | ``` 59 | 60 | 61 | 62 | ![image4](images\image4.PNG) 63 | 64 | 65 | 66 | ## 2. matplotlib圖片構造 67 | 68 | 69 | 70 | ### matplotlib圖片構造 71 | 72 | 73 | 74 | 在開始講解任何用法前(plt/ax/fig),我想先帶大家瞭解matplotlib圖片構造 75 | 76 | ![../_images/fig_map.png](https://matplotlib.org/1.5.1/_images/fig_map.png) 77 | 78 | 圖片來源: 官網(https://matplotlib.org/1.5.1/faq/usage_faq.html#parts-of-a-figure) 79 | 80 | 81 | 82 | + 圖片講解 83 | 84 | + Figure: 指的是畫布,也就是當我們要畫圖時,要先創建一個畫布,才能在上面加上各種圖片(元素) 85 | 86 | ```Python 87 | fig = plt.figure() 88 | ``` 89 | 90 | 91 | 92 | + Axes: 93 | 94 | + axis是指x或y軸,而axes指的是複數形式(二維就有兩個座標軸、三維就有三個),也就是figure中一個元素(圖片)的整套座標軸 95 | + 比喻: Figure為畫布,axes就是你要放到畫布上的任何物體,像是我們要畫小河、學校、公園,學校就是一個axes,公園與小河也個別是一個axes 96 | 97 | + 每次我們在figure中增加一個subplot,其實就是增加一套座標軸 98 | 99 | + 所以如果今天figure中只有一張圖,那ax...和plt....控制的圖片就是一樣的,效果也會是一樣的(解惑了我們一開始的問題) 100 | 101 | 102 | 103 | + Axis: `ax.axis / ax.yaxis` 104 | 105 | + x,y坐標軸 106 | 107 | + 每個坐標軸由豎線和數字構成(就是我們的刻度和值),而每個豎線也為一個axis的subplot,所以ax.xaxis也有axes這個對象,對每個axes進行編輯就會影響xaxis圖片上的樣子 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | ### **關鍵字: matplotlib圖片中的各個部位名稱** 116 | 117 | 118 | 119 | 有了這張圖我們可以根據要進行修改的部分,依照圖片上的名稱進行查詢如何編輯 120 | 121 | ![../../_images/anatomy.png](https://matplotlib.org/_images/anatomy.png) 122 | 123 | 圖片來源: 官網(https://matplotlib.org/tutorials/introductory/usage.html) 124 | 125 | 126 | 127 | 128 | 129 | ## 3. plt 與 ax 的差別 130 | 131 | 132 | 133 | Matplotlib中,兩種畫圖的方式 134 | 135 | 136 | 137 | + plt.figure(): 這是matplotlib所提供的一個api,可以快速地透過plt.來畫圖,但如果想要更細緻,也就是控制到更細的部分來畫圖,就要使用第二種方法 138 | 139 | ```Pythonimport matplotlib.pyplot as plt 140 | import matplotlib.pyplot as plt 141 | 142 | x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 143 | y = [66, 28, 32, 58, 18, 2, 99, 77, 66, 58] 144 | 145 | plt.figure(figsize = (10, 10)) 146 | plt.subplot(221) 147 | 148 | 149 | plt.plot(x, y) 150 | plt.title('Method 1') 151 | 152 | plt.show() 153 | ``` 154 | 155 | ![image5](images\image5.PNG) 156 | 157 | 158 | 159 | + fig, ax = plt.subplots(): 透過指定figure和axes來進行畫圖,對axes進行單獨更細緻的操作 160 | 161 | ```Python 162 | import matplotlib.pyplot as plt 163 | 164 | x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 165 | y = [66, 28, 32, 58, 18, 2, 99, 77, 66, 58] 166 | 167 | fig, ax = plt.subplots(figsize = (10, 10)) 168 | 169 | ax.plot(x, y) 170 | ax.set_title('Method 2') 171 | 172 | plt.show() 173 | ``` 174 | 175 | 176 | 177 | ![image6](images\image6.PNG) 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | ## 4. 簡單實作一下 190 | 191 | 192 | 193 | ### Step1: 導入套件和創建數據 194 | 195 | 196 | 197 | ```Python 198 | import matplotlib.pyplot as plt 199 | 200 | x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 201 | y1 = [66, 28, 32, 58, 18, 2, 99, 77, 66, 58] 202 | y2 = [58,2,8,10,66,32,28,58,66,66] 203 | 204 | ``` 205 | 206 | 207 | 208 | 209 | 210 | ### Step2: 創建畫布 211 | 212 | ```Python 213 | fig, ax = plt.subplots(figsize = (10, 10)) 214 | ``` 215 | 216 | 217 | 218 | ### Step3: 畫圖 219 | 220 | ```Python 221 | ax.plot(x, y1) 222 | ax.plot(x, y2) 223 | ``` 224 | 225 | ![step1](images\step1.PNG) 226 | 227 | 228 | 229 | ### Step4: 設定標題 230 | 231 | ```Python 232 | ## 標題 233 | ax.set_title('Method 2') 234 | ax.set_xlabel('Label X', fontsize = 'x-large', fontfamily = 'sans-serif', color = 'white', fontstyle = 'italic') 235 | ax.set_ylabel('Label Y', fontsize = 10, fontfamily = 'sans-serif', color = 'blue', fontstyle = 'oblique') 236 | ``` 237 | 238 | ![step2](images\step2.PNG) 239 | 240 | 241 | 242 | ### Step5: 設定x軸和y軸屬性 243 | 244 | ```Python 245 | ## x y軸的屬性設定 246 | ## aspect : {'auto', 'equal'} or num 247 | ax.set_aspect('auto') 248 | ## 於軸上顯示較小的刻度 249 | ax.minorticks_on() 250 | ## 設定x軸的範圍 251 | ax.set_xlim(0, 8) 252 | ## 設定網格 253 | ## which : {'major', 'minor', 'both'} 254 | ax.grid(which = 'major', axis = 'both') 255 | ``` 256 | 257 | 258 | 259 | ![step3](images\step3.PNG) 260 | 261 | ### Step6: 設定坐標軸tick和更多細節 262 | 263 | ```Python 264 | ## 設定座標軸tick和更多細節 265 | 266 | ## 設定x軸字體(旋轉、大小、顏色) 267 | ax.xaxis.set_tick_params(rotation = 50, labelsize = 20, colors = 'w') 268 | ## 取得x軸範圍 269 | start, end = ax.get_xlim() 270 | ## 設定x軸刻度以0.5為單位 271 | ax.xaxis.set_ticks(np.arange(start, end, 0.5)) 272 | ## 將y軸刻度顯示在右邊 273 | ax.yaxis.tick_right() 274 | ``` 275 | 276 | ![step4](images\step4.PNG) 277 | 278 | ### 完整程式碼 279 | 280 | 281 | 282 | ```Python 283 | import matplotlib.pyplot as plt 284 | import numpy as np 285 | 286 | 287 | x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 288 | y1 = [66, 28, 32, 58, 18, 2, 99, 77, 66, 58] 289 | y2 = [58,2,8,10,66,32,28,58,66,66] 290 | 291 | 292 | fig, ax = plt.subplots(figsize = (10, 10)) 293 | 294 | ax.plot(x, y1) 295 | ax.plot(x, y2) 296 | 297 | ## 標題 298 | ax.set_title('Method 2') 299 | ax.set_xlabel('Label X', fontsize = 'x-large', fontfamily = 'sans-serif', color = 'white', fontstyle = 'italic') 300 | ax.set_ylabel('Label Y', fontsize = 10, fontfamily = 'sans-serif', color = 'blue', fontstyle = 'oblique') 301 | 302 | 303 | ## x y軸的屬性設定 304 | ## aspect : {'auto', 'equal'} or num 305 | ax.set_aspect('auto') 306 | ## 於軸上顯示較小的刻度 307 | ax.minorticks_on() 308 | ## 設定x軸的範圍 309 | ax.set_xlim(0, 8) 310 | ## 設定網格 311 | ## which : {'major', 'minor', 'both'} 312 | ax.grid(which = 'major', axis = 'both') 313 | 314 | 315 | ## 設定座標軸tick和更多細節 316 | 317 | ## 設定x軸字體(旋轉、大小、顏色) 318 | ax.xaxis.set_tick_params(rotation = 50, labelsize = 20, colors = 'w') 319 | ## 取得x軸範圍 320 | start, end = ax.get_xlim() 321 | ## 設定x軸刻度以0.5為單位 322 | ax.xaxis.set_ticks(np.arange(start, end, 0.5)) 323 | ## 將y軸刻度顯示在右邊 324 | ax.yaxis.tick_right() 325 | 326 | ## 顯示圖片 327 | plt.show() 328 | ``` 329 | 330 | 331 | 332 | 333 | 334 | 這個觀念真的讓我受用許多,我只能說太牛了xd,瞭解了這個觀念後,以後再畫圖就能很快知道現在再控制的元件是什麼,也能快速查詢其功能,當然因為觀念是不變的道理,所以很多地方會與原文相似,如果作者看到了很介意的話,隨時與我聯絡,我會馬上撤掉喔 335 | 336 | 337 | 338 | ## Reference 339 | 340 | https://zhuanlan.zhihu.com/p/93423829?fbclid=IwAR3T5a_BSi0bjZasVbTaRVmtVuBDL2T5IeBCixPXqzegwx6d2DNnkJwQ-jM 341 | 342 | https://matplotlib.org/1.5.1/faq/usage_faq.html#parts-of-a-figure 343 | 344 | https://matplotlib.org/tutorials/introductory/usage.html 345 | 346 | 347 | 348 | 349 | 350 | -------------------------------------------------------------------------------- /matplotlib/concept/images/image1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/matplotlib/concept/images/image1.PNG -------------------------------------------------------------------------------- /matplotlib/concept/images/image2.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/matplotlib/concept/images/image2.PNG -------------------------------------------------------------------------------- /matplotlib/concept/images/image3.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/matplotlib/concept/images/image3.PNG -------------------------------------------------------------------------------- /matplotlib/concept/images/image4.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/matplotlib/concept/images/image4.PNG -------------------------------------------------------------------------------- /matplotlib/concept/images/image5.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/matplotlib/concept/images/image5.PNG -------------------------------------------------------------------------------- /matplotlib/concept/images/image6.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/matplotlib/concept/images/image6.PNG -------------------------------------------------------------------------------- /matplotlib/concept/images/step1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/matplotlib/concept/images/step1.PNG -------------------------------------------------------------------------------- /matplotlib/concept/images/step2.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/matplotlib/concept/images/step2.PNG -------------------------------------------------------------------------------- /matplotlib/concept/images/step3.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/matplotlib/concept/images/step3.PNG -------------------------------------------------------------------------------- /matplotlib/concept/images/step4.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/matplotlib/concept/images/step4.PNG -------------------------------------------------------------------------------- /numpy_read-write-file/.ipynb_checkpoints/numpy_read_write_file-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 4 6 | } 7 | -------------------------------------------------------------------------------- /numpy_read-write-file/NumPy如何讀寫檔案.md: -------------------------------------------------------------------------------- 1 | # 給自己的Python小筆記 - Numpy如何讀寫檔案? - NumPy獨有的npy和npz二進制檔案格式和text(.txt)檔案格式 - 讀取/寫入教學 2 | 3 | 4 | 5 | 6 | 7 | YoYo,過去我幾乎都是用Pandas來讀寫檔案,但因為今天工作上接到別人的code,它用了NumPy的方式來讀寫檔案,我覺得超酷的,所以當然就是要來學習一下啦,今天就來教大家如何使用NumPy來讀寫二進制(Binary)格式和 text(.txt)格式的檔案喔 8 | 9 | 10 | 11 | 12 | 13 | ## 1. NumPy讀寫方法總表 14 | 15 | 16 | 17 | 18 | 19 | |方法|說明| 20 | |---|---| 21 | |numpy.save()|將array儲存到npy格式的檔案中| 22 | |numpy.savez()|多個array儲存到npz格式的檔案中| 23 | |numpy.load()|將npy或npz中的array載回| 24 | |numpy.savetxt()|以文字檔(.txt)格式儲存資料| 25 | |numpy.loadtxt()|載回文字檔資料| 26 | 27 | 28 | 29 | ## 2. 輸出的檔案說明-npy & npz 30 | 31 | 32 | 33 | + npy: 用來儲存與載入ndarray所需的資料、圖形,dtype等資訊 34 | + npzi: 與npy相同功能,但是用來存儲多個陣列 35 | 36 | 37 | 38 | 39 | 40 | ## 3. numpy.save() & load() 41 | 42 | 43 | 44 | 45 | 46 | 1. **函式** 47 | ``` 48 | save(file, arr, allow_pickle=True, fix_imports=True) 49 | ``` 50 | 51 | 52 | 53 | 2. **參數介紹** 54 | 55 | 56 | 57 | 58 | + file: 儲存的檔案名稱,副檔名為.npy,如果沒有設定會自動補上 59 | + arr: 要儲存的array 60 | 61 | + allow_pickle: 預設為True,允許使用Python Pickle來保存對象數組,不允許使用的原因為安全性(可以執行任意操作)和可移植性(pickle對象可能沒辦法在不同容器上加載),Python的pickle用於儲存或讀取前,對物件進行序列化與反序列化 62 | 63 | + fix_imports: 僅用於將Python3的對象數組轉換為Python2能兼容的pickle 64 | 65 | 66 | 67 | 68 | 69 | 3. **實作** 70 | 71 | ```Python 72 | import numpy as np 73 | 74 | ## 創建一個0到9的array 75 | x = np.arange (10) 76 | print('Save: ', x) 77 | 78 | ## 保存成npy檔 79 | np.save('numpy_sample.npy', x) 80 | 81 | ## 不特別設定副檔名,會自動存成npy檔 82 | np.save('numpy_samplel.npy', x) 83 | 84 | ## #npy 85 | y = np.load('numpy_sample.npy') 86 | print('Load': , y) 87 | ``` 88 | **執行結果** 89 | 90 | ``` 91 | Save: [0 1 2 3 4 5 6 7 8 9] 92 | Load: [0 1 2 3 4 5 6 7 8 9] 93 | ``` 94 | 95 | 96 | 97 | 98 | 99 | 4. **查看一下npy檔的內容** 100 | 101 | ```Python 102 | ## 查看一下npy裡面的內容 103 | !type numpy_sample.npy 104 | ``` 105 | **執行結果** 106 | 107 | ``` 108 | �NUMPYv{'descr': ' 177 | Array x: [0 1 2 3 4 5 6 7 8 9] 178 | Array y: [ 1. 0.54030231 -0.41614684 -0.9899925 -0.65364362 0.28366219 179 | 0.96017029 0.75390225 -0.14550003 -0.91113026] 180 | Array z: [[2 4 6] 181 | [3 5 8]] 182 | ``` 183 | 184 | 185 | 186 | 187 | 4. **查看npx的內容** 188 | ``` 189 | !type multiple_array.npz 190 | ``` 191 | **執行結果** 192 | 193 | ``` 194 | PK!|菹�� 195 | cos_array.npy���NUMPYv{'descr': '\n", 65 | "Array x: [0 1 2 3 4 5 6 7 8 9]\n", 66 | "Array y: [ 1. 0.54030231 -0.41614684 -0.9899925 -0.65364362 0.28366219\n", 67 | " 0.96017029 0.75390225 -0.14550003 -0.91113026]\n", 68 | "Array z: [[2 4 6]\n", 69 | " [3 5 8]]\n" 70 | ] 71 | } 72 | ], 73 | "source": [ 74 | "import numpy as np\n", 75 | "\n", 76 | "x= np.arange(0, 10)\n", 77 | "\n", 78 | "y = np.cos(x)\n", 79 | "\n", 80 | "z = np.array([[2,4,6], [3,5,8]])\n", 81 | "\n", 82 | "## 將多個array保存為npz\n", 83 | "## y使用了關鍵字引數 cos_array,也就是之後會透過這個指定的關鍵字獲取y值\n", 84 | "np.savez ('multiple_array.npz', x, z, cos_array = y)\n", 85 | "\n", 86 | "## 載入npz檔\n", 87 | "a = np.load('multiple_array.npz')\n", 88 | "\n", 89 | "## 顯示所有array的名稱\n", 90 | "print('Array Name: ', a.files)\n", 91 | "\n", 92 | "## 直接print載回的檔案\n", 93 | "print (a)\n", 94 | "\n", 95 | "print('Array x: ', a['arr_0'])\n", 96 | "print('Array y: ', a['cos_array'])\n", 97 | "print('Array z: ', a['arr_1'])" 98 | ] 99 | }, 100 | { 101 | "cell_type": "code", 102 | "execution_count": 8, 103 | "metadata": {}, 104 | "outputs": [ 105 | { 106 | "name": "stdout", 107 | "output_type": "stream", 108 | "text": [ 109 | "PK\u0003\u0004\u0014\u0000\u0000\u0000\u0000\u0000\u0000\u0000!\u0000|\u0018菹�\u0000\u0000\u0000�\u0000\u0000\u0000\n", 110 | "\u0000\u0014\u0000cos_array.npy\u0001\u0000\u0010\u0000�\u0000\u0000\u0000\u0000\u0000\u0000\u0000�\u0000\u0000\u0000\u0000\u0000\u0000\u0000�NUMPY\u0001\u0000v\u0000{'descr': '\n", 45 | "\n" 46 | ] 47 | } 48 | ], 49 | "source": [ 50 | "a = parse(\"HI, My name is {}, I am working in {}\", text)\n", 51 | "print(a)\n", 52 | "b = parse(\"嗨 我的名字是{},我在{}工作\",\"嗨 我的名字是阿軒,我在新竹工作\")\n", 53 | "print(b)" 54 | ] 55 | }, 56 | { 57 | "cell_type": "code", 58 | "execution_count": 113, 59 | "metadata": {}, 60 | "outputs": [ 61 | { 62 | "name": "stdout", 63 | "output_type": "stream", 64 | "text": [ 65 | "\n", 66 | "{'name': '阿軒'}\n", 67 | "阿軒\n" 68 | ] 69 | } 70 | ], 71 | "source": [ 72 | "q = parse(\"嗨 我的名字是{student[name]},我在{}工作\",\"嗨 我的名字是阿軒,我在新竹工作\")\n", 73 | "print(q)\n", 74 | "print(q['student'])\n", 75 | "print(q['student']['name'])" 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": 94, 81 | "metadata": {}, 82 | "outputs": [ 83 | { 84 | "name": "stdout", 85 | "output_type": "stream", 86 | "text": [ 87 | "Shane HsinChu\n" 88 | ] 89 | } 90 | ], 91 | "source": [ 92 | "name = a[0]\n", 93 | "city = a[1]\n", 94 | "print(name, city)" 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "execution_count": 106, 100 | "metadata": {}, 101 | "outputs": [ 102 | { 103 | "name": "stdout", 104 | "output_type": "stream", 105 | "text": [ 106 | "('Shane', 'HsinChu')\n" 107 | ] 108 | } 109 | ], 110 | "source": [ 111 | "f = parse(\"HI, My name is {}, I am working in {}\", text)\n", 112 | "print(f.fixed)" 113 | ] 114 | }, 115 | { 116 | "cell_type": "code", 117 | "execution_count": 104, 118 | "metadata": {}, 119 | "outputs": [ 120 | { 121 | "name": "stdout", 122 | "output_type": "stream", 123 | "text": [ 124 | "\n", 125 | "Shane\n", 126 | "HsinChu\n", 127 | "{'name': 'Shane', 'work': 'HsinChu'}\n" 128 | ] 129 | } 130 | ], 131 | "source": [ 132 | "c = parse(\"HI, My name is {name}, I am working in {work}\", text)\n", 133 | "print(c)\n", 134 | "print(c['name'])\n", 135 | "print(c['work'])\n", 136 | "print(c.named)" 137 | ] 138 | }, 139 | { 140 | "cell_type": "code", 141 | "execution_count": 37, 142 | "metadata": {}, 143 | "outputs": [ 144 | { 145 | "name": "stdout", 146 | "output_type": "stream", 147 | "text": [ 148 | "None\n" 149 | ] 150 | } 151 | ], 152 | "source": [ 153 | "text = \"HI, My name is Shane, I am working in HsinChu\"\n", 154 | "warning = parse(\"Hi My name is {}\",text)\n", 155 | "print(warning)" 156 | ] 157 | }, 158 | { 159 | "cell_type": "markdown", 160 | "metadata": {}, 161 | "source": [ 162 | "## Search()" 163 | ] 164 | }, 165 | { 166 | "cell_type": "code", 167 | "execution_count": 46, 168 | "metadata": {}, 169 | "outputs": [ 170 | { 171 | "data": { 172 | "text/plain": [ 173 | "" 174 | ] 175 | }, 176 | "execution_count": 46, 177 | "metadata": {}, 178 | "output_type": "execute_result" 179 | } 180 | ], 181 | "source": [ 182 | "text = \"HI, My name is Shane, I am working in HsinChu, my age is 26\"\n", 183 | "search(\"My name is {}\",text)" 184 | ] 185 | }, 186 | { 187 | "cell_type": "code", 188 | "execution_count": 41, 189 | "metadata": {}, 190 | "outputs": [ 191 | { 192 | "data": { 193 | "text/plain": [ 194 | "" 195 | ] 196 | }, 197 | "execution_count": 41, 198 | "metadata": {}, 199 | "output_type": "execute_result" 200 | } 201 | ], 202 | "source": [ 203 | "search(\"My name is {},\",text)" 204 | ] 205 | }, 206 | { 207 | "cell_type": "code", 208 | "execution_count": 47, 209 | "metadata": {}, 210 | "outputs": [ 211 | { 212 | "data": { 213 | "text/plain": [ 214 | "" 215 | ] 216 | }, 217 | "execution_count": 47, 218 | "metadata": {}, 219 | "output_type": "execute_result" 220 | } 221 | ], 222 | "source": [ 223 | "search(\"my age is {}\",text)" 224 | ] 225 | }, 226 | { 227 | "cell_type": "code", 228 | "execution_count": 48, 229 | "metadata": {}, 230 | "outputs": [ 231 | { 232 | "data": { 233 | "text/plain": [ 234 | "" 235 | ] 236 | }, 237 | "execution_count": 48, 238 | "metadata": {}, 239 | "output_type": "execute_result" 240 | } 241 | ], 242 | "source": [ 243 | "search(\"my age is {:d}\",text)" 244 | ] 245 | }, 246 | { 247 | "cell_type": "markdown", 248 | "metadata": {}, 249 | "source": [ 250 | "## findall()" 251 | ] 252 | }, 253 | { 254 | "cell_type": "code", 255 | "execution_count": 80, 256 | "metadata": {}, 257 | "outputs": [ 258 | { 259 | "data": { 260 | "text/plain": [ 261 | "'My name is Shane'" 262 | ] 263 | }, 264 | "execution_count": 80, 265 | "metadata": {}, 266 | "output_type": "execute_result" 267 | } 268 | ], 269 | "source": [ 270 | "text = \"My name is Shane\"\n", 271 | "\n", 272 | "''.join(t[0] for t in findall(\">{}<\",text))" 273 | ] 274 | }, 275 | { 276 | "cell_type": "code", 277 | "execution_count": 136, 278 | "metadata": {}, 279 | "outputs": [ 280 | { 281 | "name": "stdout", 282 | "output_type": "stream", 283 | "text": [ 284 | "Tom Ken Ham\n", 285 | "['Tom', 'Ken', 'Ham']\n", 286 | "['0', '1', '2']\n", 287 | "['22', '23', '28']\n" 288 | ] 289 | } 290 | ], 291 | "source": [ 292 | "text = \"student id:0, name:Tom, age:22, student id:1, name:Ken, age:23, student id:2, name:Ham, age:28,\"\n", 293 | "\n", 294 | "print(' '.join(s[0] for s in findall(\"name:{},\",text)))\n", 295 | "\n", 296 | "print(' '.join(s[0] for s in findall(\"name:{},\",text)).split(' '))\n", 297 | "print(' '.join(s[0] for s in findall(\"id:{},\",text)).split(' '))\n", 298 | "print(' '.join(s[0] for s in findall(\"age:{},\",text)).split(' '))" 299 | ] 300 | }, 301 | { 302 | "cell_type": "markdown", 303 | "metadata": {}, 304 | "source": [ 305 | "## compile()" 306 | ] 307 | }, 308 | { 309 | "cell_type": "code", 310 | "execution_count": 85, 311 | "metadata": {}, 312 | "outputs": [ 313 | { 314 | "name": "stdout", 315 | "output_type": "stream", 316 | "text": [ 317 | "\n" 318 | ] 319 | } 320 | ], 321 | "source": [ 322 | "from parse import compile\n", 323 | "text = \"HI, My name is Shane, I am working in HsinChu, my age is 26\"\n", 324 | "c = compile(\"My name is {},\")\n", 325 | "print(c.search(text))" 326 | ] 327 | } 328 | ], 329 | "metadata": { 330 | "kernelspec": { 331 | "display_name": "Python 3", 332 | "language": "python", 333 | "name": "python3" 334 | }, 335 | "language_info": { 336 | "codemirror_mode": { 337 | "name": "ipython", 338 | "version": 3 339 | }, 340 | "file_extension": ".py", 341 | "mimetype": "text/x-python", 342 | "name": "python", 343 | "nbconvert_exporter": "python", 344 | "pygments_lexer": "ipython3", 345 | "version": "3.7.6" 346 | } 347 | }, 348 | "nbformat": 4, 349 | "nbformat_minor": 4 350 | } 351 | -------------------------------------------------------------------------------- /parse/images/compile().PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/parse/images/compile().PNG -------------------------------------------------------------------------------- /parse/images/findall().PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/parse/images/findall().PNG -------------------------------------------------------------------------------- /parse/images/parse().PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/parse/images/parse().PNG -------------------------------------------------------------------------------- /parse/images/search().PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/parse/images/search().PNG -------------------------------------------------------------------------------- /parse/learning_parse.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## import parse package" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 2, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "from parse import *" 17 | ] 18 | }, 19 | { 20 | "cell_type": "markdown", 21 | "metadata": {}, 22 | "source": [ 23 | "## Parse () function" 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "execution_count": 91, 29 | "metadata": {}, 30 | "outputs": [], 31 | "source": [ 32 | "text = \"HI, My name is Shane, I am working in HsinChu\"" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": 107, 38 | "metadata": {}, 39 | "outputs": [ 40 | { 41 | "name": "stdout", 42 | "output_type": "stream", 43 | "text": [ 44 | "\n", 45 | "\n" 46 | ] 47 | } 48 | ], 49 | "source": [ 50 | "a = parse(\"HI, My name is {}, I am working in {}\", text)\n", 51 | "print(a)\n", 52 | "b = parse(\"嗨 我的名字是{},我在{}工作\",\"嗨 我的名字是阿軒,我在新竹工作\")\n", 53 | "print(b)" 54 | ] 55 | }, 56 | { 57 | "cell_type": "code", 58 | "execution_count": 113, 59 | "metadata": {}, 60 | "outputs": [ 61 | { 62 | "name": "stdout", 63 | "output_type": "stream", 64 | "text": [ 65 | "\n", 66 | "{'name': '阿軒'}\n", 67 | "阿軒\n" 68 | ] 69 | } 70 | ], 71 | "source": [ 72 | "q = parse(\"嗨 我的名字是{student[name]},我在{}工作\",\"嗨 我的名字是阿軒,我在新竹工作\")\n", 73 | "print(q)\n", 74 | "print(q['student'])\n", 75 | "print(q['student']['name'])" 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": 94, 81 | "metadata": {}, 82 | "outputs": [ 83 | { 84 | "name": "stdout", 85 | "output_type": "stream", 86 | "text": [ 87 | "Shane HsinChu\n" 88 | ] 89 | } 90 | ], 91 | "source": [ 92 | "name = a[0]\n", 93 | "city = a[1]\n", 94 | "print(name, city)" 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "execution_count": 106, 100 | "metadata": {}, 101 | "outputs": [ 102 | { 103 | "name": "stdout", 104 | "output_type": "stream", 105 | "text": [ 106 | "('Shane', 'HsinChu')\n" 107 | ] 108 | } 109 | ], 110 | "source": [ 111 | "f = parse(\"HI, My name is {}, I am working in {}\", text)\n", 112 | "print(f.fixed)" 113 | ] 114 | }, 115 | { 116 | "cell_type": "code", 117 | "execution_count": 104, 118 | "metadata": {}, 119 | "outputs": [ 120 | { 121 | "name": "stdout", 122 | "output_type": "stream", 123 | "text": [ 124 | "\n", 125 | "Shane\n", 126 | "HsinChu\n", 127 | "{'name': 'Shane', 'work': 'HsinChu'}\n" 128 | ] 129 | } 130 | ], 131 | "source": [ 132 | "c = parse(\"HI, My name is {name}, I am working in {work}\", text)\n", 133 | "print(c)\n", 134 | "print(c['name'])\n", 135 | "print(c['work'])\n", 136 | "print(c.named)" 137 | ] 138 | }, 139 | { 140 | "cell_type": "code", 141 | "execution_count": 37, 142 | "metadata": {}, 143 | "outputs": [ 144 | { 145 | "name": "stdout", 146 | "output_type": "stream", 147 | "text": [ 148 | "None\n" 149 | ] 150 | } 151 | ], 152 | "source": [ 153 | "text = \"HI, My name is Shane, I am working in HsinChu\"\n", 154 | "warning = parse(\"Hi My name is {}\",text)\n", 155 | "print(warning)" 156 | ] 157 | }, 158 | { 159 | "cell_type": "markdown", 160 | "metadata": {}, 161 | "source": [ 162 | "## Search()" 163 | ] 164 | }, 165 | { 166 | "cell_type": "code", 167 | "execution_count": 46, 168 | "metadata": {}, 169 | "outputs": [ 170 | { 171 | "data": { 172 | "text/plain": [ 173 | "" 174 | ] 175 | }, 176 | "execution_count": 46, 177 | "metadata": {}, 178 | "output_type": "execute_result" 179 | } 180 | ], 181 | "source": [ 182 | "text = \"HI, My name is Shane, I am working in HsinChu, my age is 26\"\n", 183 | "search(\"My name is {}\",text)" 184 | ] 185 | }, 186 | { 187 | "cell_type": "code", 188 | "execution_count": 41, 189 | "metadata": {}, 190 | "outputs": [ 191 | { 192 | "data": { 193 | "text/plain": [ 194 | "" 195 | ] 196 | }, 197 | "execution_count": 41, 198 | "metadata": {}, 199 | "output_type": "execute_result" 200 | } 201 | ], 202 | "source": [ 203 | "search(\"My name is {},\",text)" 204 | ] 205 | }, 206 | { 207 | "cell_type": "code", 208 | "execution_count": 47, 209 | "metadata": {}, 210 | "outputs": [ 211 | { 212 | "data": { 213 | "text/plain": [ 214 | "" 215 | ] 216 | }, 217 | "execution_count": 47, 218 | "metadata": {}, 219 | "output_type": "execute_result" 220 | } 221 | ], 222 | "source": [ 223 | "search(\"my age is {}\",text)" 224 | ] 225 | }, 226 | { 227 | "cell_type": "code", 228 | "execution_count": 48, 229 | "metadata": {}, 230 | "outputs": [ 231 | { 232 | "data": { 233 | "text/plain": [ 234 | "" 235 | ] 236 | }, 237 | "execution_count": 48, 238 | "metadata": {}, 239 | "output_type": "execute_result" 240 | } 241 | ], 242 | "source": [ 243 | "search(\"my age is {:d}\",text)" 244 | ] 245 | }, 246 | { 247 | "cell_type": "markdown", 248 | "metadata": {}, 249 | "source": [ 250 | "## findall()" 251 | ] 252 | }, 253 | { 254 | "cell_type": "code", 255 | "execution_count": 80, 256 | "metadata": {}, 257 | "outputs": [ 258 | { 259 | "data": { 260 | "text/plain": [ 261 | "'My name is Shane'" 262 | ] 263 | }, 264 | "execution_count": 80, 265 | "metadata": {}, 266 | "output_type": "execute_result" 267 | } 268 | ], 269 | "source": [ 270 | "text = \"My name is Shane\"\n", 271 | "\n", 272 | "''.join(t[0] for t in findall(\">{}<\",text))" 273 | ] 274 | }, 275 | { 276 | "cell_type": "code", 277 | "execution_count": 136, 278 | "metadata": {}, 279 | "outputs": [ 280 | { 281 | "name": "stdout", 282 | "output_type": "stream", 283 | "text": [ 284 | "Tom Ken Ham\n", 285 | "['Tom', 'Ken', 'Ham']\n", 286 | "['0', '1', '2']\n", 287 | "['22', '23', '28']\n" 288 | ] 289 | } 290 | ], 291 | "source": [ 292 | "text = \"student id:0, name:Tom, age:22, student id:1, name:Ken, age:23, student id:2, name:Ham, age:28,\"\n", 293 | "\n", 294 | "print(' '.join(s[0] for s in findall(\"name:{},\",text)))\n", 295 | "\n", 296 | "print(' '.join(s[0] for s in findall(\"name:{},\",text)).split(' '))\n", 297 | "print(' '.join(s[0] for s in findall(\"id:{},\",text)).split(' '))\n", 298 | "print(' '.join(s[0] for s in findall(\"age:{},\",text)).split(' '))" 299 | ] 300 | }, 301 | { 302 | "cell_type": "markdown", 303 | "metadata": {}, 304 | "source": [ 305 | "## compile()" 306 | ] 307 | }, 308 | { 309 | "cell_type": "code", 310 | "execution_count": 85, 311 | "metadata": {}, 312 | "outputs": [ 313 | { 314 | "name": "stdout", 315 | "output_type": "stream", 316 | "text": [ 317 | "\n" 318 | ] 319 | } 320 | ], 321 | "source": [ 322 | "from parse import compile\n", 323 | "text = \"HI, My name is Shane, I am working in HsinChu, my age is 26\"\n", 324 | "c = compile(\"My name is {},\")\n", 325 | "print(c.search(text))" 326 | ] 327 | } 328 | ], 329 | "metadata": { 330 | "kernelspec": { 331 | "display_name": "Python 3", 332 | "language": "python", 333 | "name": "python3" 334 | }, 335 | "language_info": { 336 | "codemirror_mode": { 337 | "name": "ipython", 338 | "version": 3 339 | }, 340 | "file_extension": ".py", 341 | "mimetype": "text/x-python", 342 | "name": "python", 343 | "nbconvert_exporter": "python", 344 | "pygments_lexer": "ipython3", 345 | "version": "3.7.6" 346 | } 347 | }, 348 | "nbformat": 4, 349 | "nbformat_minor": 4 350 | } 351 | -------------------------------------------------------------------------------- /parse/readme.md: -------------------------------------------------------------------------------- 1 | ### Download Parse Package 2 | 3 | + pip install Parse 4 | 5 | 6 | 7 | ### parse() 8 | 9 | + using parse function to parse the data you want in the text(type(str)) 10 | + load into a dictionary type , then you can easily find the data you want 11 | + Warning : the length of the text must be same as the parse you are writing, otherwise it won't parse any thing down 12 | 13 | ![parse()](https://github.com/chwang12341/Learn-Python-/blob/master/parse/images/parse().PNG?raw=true) 14 | 15 | ### search() 16 | 17 | + solve the problem we met in parse() 18 | + use the pattern to find out the data we want 19 | + I will show some scenario of using it in my tool repo 20 | 21 | ![images](https://github.com/chwang12341/Learn-Python-/blob/master/parse/images/search().PNG?raw=true) 22 | 23 | 24 | 25 | ### findall() 26 | 27 | + parsing the web page easily 28 | + you can easily put the data you want into list 29 | 30 | ![images](https://github.com/chwang12341/Learn-Python-/blob/master/parse/images/findall().PNG?raw=true) 31 | 32 | 33 | 34 | 35 | 36 | ### compile() 37 | 38 | + If you have a lot of same thing to parse 39 | 40 | ![images](https://github.com/chwang12341/Learn-Python-/blob/master/parse/images/compile().PNG?raw=true) 41 | 42 | *reference: * -------------------------------------------------------------------------------- /pathlib/Readme.md: -------------------------------------------------------------------------------- 1 | # Coding起來 - Python pathlib模組 - 快來學習超好用的檔案與資料夾操作模組 2 | 3 | 4 | 5 | 6 | 7 | ## 1. 動機 - 為什麼要用pathlib? 8 | 9 | 10 | 11 | 過去我在執行有關路徑的操作,幾乎都是使用os.path,但是因為工作的關係常常會面臨一個問題,就是我的Python要在Windows跟Linux間進行操作,每次都因`\`問題要修改來改去,所以同事就推薦我一個相當好用的模组pathlib 12 | 13 | **路徑 / 問題:** 14 | 15 | + Windows作業系統: 我們的路徑會用反斜線`\` 16 | 17 | + Mac/Linux作業系統: 我們的檔將路徑會是前斜線`/` 18 | 19 | 它不只在出理檔案路徑上相當方便,個人覺得它的系統操作,像是檔案讀寫、確認檔案是否存在、列出資料夾內的所有檔案都是相當方便的 20 | 21 | 22 | 23 | 24 | 25 | ## 2. pathlib是什麼? 26 | 27 | + pathlib將各種檔案與資料夾相關的操作全部封装在Path、WindowPath PosixPath類別中,讓檔案與資料夾的操作更加物件導向 28 | 29 | 簡單來說就是方便我們進行各種檔案與資料夾操作的模組 30 | 31 | 32 | 33 | 34 | 35 | ## 3. pathlib底下的類別有哪些? 36 | 37 | 38 | 39 | 40 | ![../_images/pathlib-inheritance.png](https://docs.python.org/3/_images/pathlib-inheritance.png) 41 | 42 | 圖片來源:官網 43 | 44 | + Path: 為PurePath的子類別,該類別用來表示系統路徑風格的具體路徑(實例化後,它會創建 PosixPath或是WindowsPath,這要看大家的作業系統) 45 | + PosixPath: 為Path與PurePosixPath的子類,此類別用來表示具體的非Windows文件系统路徑 46 | 47 | + WindowsPath: 為Path與PureWindowsPath的子類,此類別用來表示具體的Windows文件系统路徑 48 | 49 | 提醒: 大家在實作的時候,其實不用特別用PosixPath跟WindowsPath,只要使用Path,它就會根據我們的作業系統來幫助我們創建對的Path類別喔 50 | 51 | **補充:PurePath vs Path** 52 | 53 | + Path是PurePath的子類別 54 | + PurePath可用的函式,Path也都能夠調用 55 | 56 | **主要差別:** 57 | 58 | + PurePath主要是用來提供檔案路徑的方便字符串處理 59 | + Path是PurePath再加上System Calle操作,也就是透過Path才有辦法與我們的作業系統互動,像是讀寫檔案、查看使用者的home目錄、檢查指定檔案有無存在,創建資料夾等等 60 | 61 | 62 | 63 | 64 | 65 | ## 4. Path的各種操作 66 | 67 | 68 | 69 | ### 導入Path套件 70 | 71 | ```Python 72 | ## 導入Path套件 73 | from pathlib import Path 74 | ``` 75 | 76 | 77 | ### 導入我們的測試檔案路徑 78 | 79 | + 傳遞一個檔案的完整路徑到Path 80 | 81 | ```Python 82 | path = Path('C:\pathlib') 83 | print(type(path)) 84 | print(path) 85 | ``` 86 | 執行結果 87 | 88 | ``` 89 | 90 | C:\pathlib 91 | ``` 92 | 93 | 結果: 由於我用的是Windows作業系統,所以大家可以看到Path會自動幫我建立一個WindowsPath類別 94 | 95 | 96 | 97 | 98 | 99 | ### 取得檔案名/副檔名 100 | 101 | **重要: 這邊有一個[cheat sheet] 102 | (https://github.com/chris1610/pbpython/blob/master/extras/Pathlib-Cheatsheel.pdf)可以馬上找到自己想要在檔案路徑中取得的資訊** 103 | 104 | ```Python 105 | f_path = Path('C:/pathlib/data/test.txt') 106 | 107 | ## 取得檔案全名 108 | print(f_path.name) 109 | ## 取得檔案副檔名 110 | print(f_path.suffix) 111 | ## 取得檔案名 112 | print(f_path.stem) 113 | ## 如果有多個副檔名的狀況 114 | print(Path('test.txt.gz').suffixes) 115 | ``` 116 | 117 | 執行結果 118 | ``` 119 | test.txt 120 | .txt 121 | test 122 | ['.txt', '.gz'] 123 | ``` 124 | 125 | ### 取得各種檔案路徑 126 | 127 | ```Python 128 | ## 取得檔案路徑 129 | print(f_path.parent) 130 | ## 取得一層一層的路徑 131 | print(list(f_path.parents)) 132 | ## 把檔案路徑轉換成uri格式 133 | print(f_path.as_uri()) 134 | ## 取得絕對路徑 135 | print(f_path.absolute()) 136 | ## 取得路徑中最開始的位置 通常就是我們的磁碟機位置 137 | print(f_path.drive) 138 | ``` 139 | 140 | 執行結果 141 | 142 | ``` 143 | C:\pathlib\data 144 | [WindowsPath('C:/pathlib/data'), WindowsPath('C:/pathlib'), WindowsPath('C:/')] 145 | file:///C:/pathlib/data/test.txt 146 | C:\pathlib\data\test.txt 147 | C: 148 | ``` 149 | 150 | 151 | 152 | 153 | ### 檢查給定的檔案/資料夾是否存在 154 | 155 | 重要觀念: 不管我們傳進的路徑是否真的有這個檔案,Path都能指向它,並做到一些操作,所以我們要去檢查檔案是真的存在我們的電腦裡面 156 | 157 | ```Python 158 | ## 檢查檔案是否存在 159 | print(f_path.exists()) 160 | folder = Path('C:/pathlib/data') 161 | print(folder.exists()) 162 | new_file = Path('C:/projects/pathlib_learning/hello.txt') 163 | print (new_file.exists()) 164 | new_folder = Path('C:/project/hello/') 165 | print(new_folder.exists()) 166 | ``` 167 | 執行結果 168 | 169 | ``` 170 | True 171 | True 172 | False 173 | False 174 | ``` 175 | 176 | 177 | 178 | 179 | 180 | ### 建立和刪除檔案 181 | 182 | ```Python 183 | ## 檢查檔案是否存在 184 | new_file = Path('C:/pathlib/data/testl.txt') 185 | print (new_file.exists()) 186 | ## 創建檔案 187 | new_file.touch() 188 | ## 檢查檔案是否存在 189 | print (new_file.exists()) 190 | ## 刪除檔案 191 | new_file.unlink() 192 | ## 檢查檔案是否存在 193 | print(new_file.exists()) 194 | ``` 195 | 196 | 執行結果 197 | 198 | ``` 199 | False 200 | True 201 | False 202 | ``` 203 | 204 | 205 | 206 | ### 判斷是否為檔案、資料夾、Unix Socket - is_file, is_dir, is_socket 207 | 208 | ```Python 209 | ## 創建一個test3檔案 210 | p = Path('C:/pathlib/data/', 'test3.txt') 211 | p.touch() 212 | ## 判斷是否為檔案 213 | print (p.is_file()) 214 | ## 判斷是否為資料夾 215 | print (p.is_dir()) 216 | ## 判斷路徑是否指向Unix socket檔案 217 | print(p.is_socket()) 218 | ``` 219 | 220 | 執行結果 221 | 222 | ``` 223 | True 224 | False 225 | False 226 | ``` 227 | 228 | 229 | 230 | 更多判斷: 大家可以直接參考(https://docs.python.org/3/library/pathlib.html#pathlib_Path.is_file) 裡面有更多判斷的用法 231 | 232 | 233 | 234 | 235 | 236 | ### 寫入/讀取檔案 237 | 238 | 提醒: 這邊我們再來執行一次write_text,它並不會附加在我們之前寫進的資料後面,而是會覆寫它喔 239 | 240 | ```Python 241 | ## 寫進Good 242 | print(p.write_text('Good')) 243 | ## 寫進Morning 244 | print (p.write_text('Morning')) 245 | ## 讀取檔案內容 246 | print (p.read_text()) 247 | ``` 248 | 249 | 執行結果 250 | 251 | ``` 252 | 4 253 | 7 254 | Morning 255 | ``` 256 | 257 | 258 | 259 | 260 | 261 | 262 | Path也支援我們常用的讀寫檔案方法 - with open() as 263 | 264 | ```Python 265 | ## with open() as 方法 266 | with p.open('w') as f: 267 | f.write('Good') 268 | p.read_text() 269 | ``` 270 | 271 | 執行結果 272 | 273 | ``` 274 | 'Good' 275 | ``` 276 | 277 | 278 | 279 | ### 獲取檔案大小 280 | 281 | ```Python 282 | ## 獲取檔案資訊 283 | print(p.stat()) 284 | ## 取得檔寮大小 285 | print(p.stat().st_size) 286 | ``` 287 | 執行結果 288 | ``` 289 | os.stat_result(st_mode=33206, st_ino=30962247438309046, st_dev=477207366, st_nlink=1, st_uid=0, st_gid=0, st_size=4, st_atime=1630227096, st_mtime=1630227096, st_ctime=1630227021) 290 | 4 291 | ``` 292 | 293 | 294 | 結果表示檔案大小為4bytes 295 | 296 | 297 | 298 | 299 | 300 | ### 讀取資料夾內所有檔案與資料夾 - iterdir() 301 | 302 | ```Python 303 | # 獲取資料夾中所有檔案 304 | for f in Path('files').iterdir(): 305 | print(type(f), f) 306 | ``` 307 | 執行結果 308 | ``` 309 | files\a 310 | files\b.txt 311 | files\c.csv 312 | files\d.docx 313 | files\e.csv 314 | files\f.csv 315 | ``` 316 | 317 | 318 | 319 | 320 | 321 | ### 對路徑進行操作 - 結合、判斷 322 | 323 | ```Python 324 | ## 透過/來結合路徑 325 | p = Path('C:/') 326 | print(p / 'test3.txt') 327 | print(p/ 'pathlib' / 'data' / 'test3.txt') 328 | print (p/Path('pathlib') / 'data' / Path('test3.txt')) 329 | ## 判斷語句 - 判斷檔案路徑是否一樣 330 | print(Path('C:/test.txt') == Path('C:/test.txt')) 331 | print(Path('C:/test.txt') == Path('c: /testl.txt')) 332 | ``` 333 | 334 | 執行結果 335 | 336 | ``` 337 | C:\test3.txt 338 | C:\pathlib\data\test3.txt 339 | C:\pathlib\data\test3.txt 340 | True 341 | False 342 | ``` 343 | 344 | 345 | 346 | 347 | 348 | ## 補充: 工作上可能會遇到的情境 349 | 350 | 351 | 352 | 情境: 當我們需要讀取某個資料夾中的所有csv檔,但是資料夾裡面可能有各種檔案類型,那我們需要怎麼處理? 353 | 354 | 其實很簡單,就是加上一個副檔名來判斷 355 | 356 | 357 | 358 | ```Python 359 | ## 獲取資料夾中所有為csv的檔案 360 | csv_files = [] 361 | for f in Path('files').iterdir(): 362 | if f.suffix == '.csv': 363 | csv_files.append(str(f)) 364 | csv_files 365 | ``` 366 | 執行結果 367 | 368 | ``` 369 | ['files\\c.csv', 'files\\e.csv', 'files\\f.csv'] 370 | ``` 371 | 372 | 373 | 374 | pathlib當然還有很多種方法可以使用!我這邊就先列出我覺得大家可能比較常遇到的問題,如果大家想要了解更進階的操作,再請大家參考官網了喔 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | ## Reference 383 | https://docs.python.org/3/library/pathlib.html 384 | https://github.com/chris1610/pbpython/blob/master/extras/Pathlib-Cheatsheet.pdf 385 | https://docs.python.org/zh-cn/3/library/pathlib.html 386 | https://docs.python.org/3/library/pathlib.html#pathlib.PosixPath 387 | -------------------------------------------------------------------------------- /pathlib/data/test.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/pathlib/data/test.txt -------------------------------------------------------------------------------- /pathlib/data/test3.txt: -------------------------------------------------------------------------------- 1 | Good -------------------------------------------------------------------------------- /pathlib/files/b.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/pathlib/files/b.txt -------------------------------------------------------------------------------- /pathlib/files/c.csv: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /pathlib/files/d.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/pathlib/files/d.docx -------------------------------------------------------------------------------- /pathlib/files/e.csv: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /pathlib/files/f.csv: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /pathlib/pathlib.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "## 導入Path套件\n", 10 | "from pathlib import Path" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": 4, 16 | "metadata": {}, 17 | "outputs": [ 18 | { 19 | "ename": "SyntaxError", 20 | "evalue": "(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \\UXXXXXXXX escape (, line 1)", 21 | "output_type": "error", 22 | "traceback": [ 23 | "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m path = Path('C:\\Users\\user\\Desktop')\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \\UXXXXXXXX escape\n" 24 | ] 25 | } 26 | ], 27 | "source": [ 28 | "path = Path('C:\\Users\\user\\Desktop')\n", 29 | "print(type(path))\n", 30 | "print(path)" 31 | ] 32 | } 33 | ], 34 | "metadata": { 35 | "kernelspec": { 36 | "display_name": "Python 3", 37 | "language": "python", 38 | "name": "python3" 39 | }, 40 | "language_info": { 41 | "codemirror_mode": { 42 | "name": "ipython", 43 | "version": 3 44 | }, 45 | "file_extension": ".py", 46 | "mimetype": "text/x-python", 47 | "name": "python", 48 | "nbconvert_exporter": "python", 49 | "pygments_lexer": "ipython3", 50 | "version": "3.7.6" 51 | } 52 | }, 53 | "nbformat": 4, 54 | "nbformat_minor": 4 55 | } 56 | -------------------------------------------------------------------------------- /pytest-fixture/__pycache__/test_fixture_learning.cpython-37-pytest-5.4.3.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/pytest-fixture/__pycache__/test_fixture_learning.cpython-37-pytest-5.4.3.pyc -------------------------------------------------------------------------------- /pytest-fixture/test_fixture_learning.py: -------------------------------------------------------------------------------- 1 | ## test_fixture_learning.py 2 | ## 基本用法 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  3 | 4 | ## test_fixture_learning.py 5 | ##import package 6 | # import pytest 7 | # @pytest.fixture 8 | # def sea_animal(): 9 | # return"Turtles" 10 | # @pytest.fixture 11 | # def farm_animal(): 12 | # return "dogs" 13 | # def forest_animal(): 14 | # return "Monkey" 15 | # def test_turtle_in_sea(sea_animal): 16 | # assert "Turtles" == sea_animal ## fixture 用法 17 | # assert "Monkey" == forest_animal() ## 沒有ficture的用法 18 | 19 | # def test_c_in_sea(sea_animal): 20 | # assert "t" in sea_animal ## fixture 用法 21 | # assert "M" in forest_animal() ## 沒有ficture的用法 22 | # def test_two_func_in_one(sea_animal,farm_animal): 23 | # assert "s" in sea_animal and farm_animal 24 | # assert "Turtles" == sea_animal 25 | # assert "dogs" == farm_animal 26 | 27 | 28 | 29 | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 30 | ## Scope 用法 與 class 無法代入參數的解決方法 - - - - - - - - - - - - - - - - - - - - - - - 31 | ## test_fixture_learning.py 32 | import pytest 33 | @pytest.fixture(scope="function") 34 | def scope_func(): 35 | pass 36 | @pytest.fixture(scope="class") 37 | def scope_class(): 38 | pass 39 | @pytest.fixture(scope="module") 40 | def scope_module(): 41 | pass 42 | @pytest.fixture(scope= "session") 43 | def scope_session(): 44 | pass 45 | ## function method 46 | def test_scope1(scope_func, scope_class, scope_module, scope_session): 47 | assert scope_func == None 48 | assert scope_class == None 49 | def tes_scope2(scope_class, scope_module, scope_session): 50 | pass 51 | 52 | 53 | ## class method  54 | @pytest.mark.usefixtures() 55 | class TestClassMethod: 56 | def test_scope3(self, scope_func, scope_class, scope_module, scope_session): 57 | assert scope_func== None 58 | def test_scope4(self, scope_class, scope_module): 59 | pass 60 | 61 | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 62 | ## Fixture decorator - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  63 | # import pytest 64 | # @pytest.fixture 65 | # def decorator_implement(): 66 | # print('\nHappend before each test start') 67 | # def sea_animal(): 68 | # return"Turtles" 69 | # @pytest.fixture 70 | # def farm_animal(): 71 | # return "dogs" 72 | # ## function  73 | # @pytest.mark.usefixtures("decorator_implement") 74 | # def test1(): 75 | # print("test 1") 76 | # assert "Turtles" == sea_animal() 77 | 78 | # @pytest.mark.usefixtures("decorator_implement") 79 | # def test2(farm_animal): 80 | # print("test 2") 81 | # assert "dogs" == farm_animal 82 | # ## class: inside 83 | # class Test_Decorator: 84 | # @pytest.mark.usefixtures("decorator_implement") 85 | # def test3(self): 86 | # print("test 3") 87 | # assert "Turtles" == sea_animal() 88 | 89 | # @pytest.mark.usefixtures("decorator_implement") 90 | # def test4(self, farm_animal): 91 | # print("test 4") 92 | # assert "dogs" == farm_animal 93 | # ## class: outside 94 | # @pytest.mark.usefixtures("decorator_implement") 95 | # class Test_Decorator1: 96 | 97 | # def test5(self): 98 | # print("test 5") 99 | # assert "Turtles" == sea_animal() 100 | 101 | # def test6(self, farm_animal): 102 | # print("test 6") 103 | # assert "dogs" == farm_animal 104 | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 105 | ## Autos 用法 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  106 | ## test_fixture_learning.py 107 | # import time 108 | # import pytest 109 | # @pytest.fixture(scope="session", autouse=True) 110 | # def session_range(): 111 | # print("\n") 112 | # print("Session Range") 113 | # # print(request.module.__name__) 114 | # # print(time.asctime()) 115 | 116 | # @pytest.fixture(scope="class", autouse=True) 117 | # def class_range(): 118 | # print("\n") 119 | # print("Class Range") 120 | # # print(request.function.__name__) 121 | # # print(time.asctime()) 122 | # @pytest.fixture(scope="function", autouse=True) 123 | # def function_range(): 124 | # print("\n") 125 | # print("Function Range") 126 | # # print(request.function.__name__) 127 | # # print(time.asctime()) 128 | # def test1(): 129 | # print("Test 1") 130 | 131 | 132 | # def test2(): 133 | # print("Test 2") 134 | 135 | 136 | # class TestClass: 137 | # def test3(self): 138 | # print("Test 3") 139 | # def test4(self): 140 | # print("Test 4") 141 | # def test5(self): 142 | # print("Test 5") 143 | # def test6(self): 144 | # print("Test 6") 145 | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  146 | # ## Fixture 回傳Value: params 用法 - - - - - - - - - - - - - - - - - - - - - - - - - - - -  147 | # ## test_fixture_learning.py 148 | # import pytest 149 | # @pytest.fixture(params=[2,58,6,"Hi"]) 150 | # def test_create_params(request): 151 | #  return request.param 152 | # def test_params(test_create_params): 153 | #  print(test_create_params) 154 | #  assert test_create_params != 8 155 | ## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -------------------------------------------------------------------------------- /pytest/__pycache__/test_pytest_learning_function-except.cpython-37-pytest-5.4.3.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/pytest/__pycache__/test_pytest_learning_function-except.cpython-37-pytest-5.4.3.pyc -------------------------------------------------------------------------------- /pytest/__pycache__/test_pytest_learning_function.cpython-37-pytest-5.4.3.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/pytest/__pycache__/test_pytest_learning_function.cpython-37-pytest-5.4.3.pyc -------------------------------------------------------------------------------- /pytest/test/test_a_2.py: -------------------------------------------------------------------------------- 1 | ## test_a_2.py 2 | ## Import package 3 | import pytest 4 | @pytest.mark.run(order=5) 5 | def test_fifth_func(): 6 | print('Order 5 Function') 7 | 8 | @pytest.mark.run(order=6) 9 | def test_Sixth_func(): 10 | print('Order 6 Function') 11 | 12 | 13 | @pytest.mark.run(order=7) 14 | def test_Seventh_func(): 15 | print('Order 7 Function') 16 | 17 | @pytest.mark.run(order=8) 18 | def test_Eigth_func(): 19 | print('Order 8 Function') -------------------------------------------------------------------------------- /pytest/test/test_b_1.py: -------------------------------------------------------------------------------- 1 | ## test_b_1.py 2 | ## Import package 3 | import pytest 4 | @pytest.mark.run(order=1) 5 | def test_first_func(): 6 | print('Order 1 Function') 7 | 8 | @pytest.mark.run(order=2) 9 | def test_Second_func(): 10 | print('Order 2 Function') 11 | 12 | 13 | @pytest.mark.run(order=3) 14 | def test_Third_func(): 15 | print('Order 3 Function') 16 | 17 | @pytest.mark.run(order=4) 18 | def test_Forth_func(): 19 | print('Order 4 Function') -------------------------------------------------------------------------------- /pytest/test_pytest_learning_function-except.py: -------------------------------------------------------------------------------- 1 | ##test_pytest_learning_function-except.py 2 | 3 | 4 | ##import package 5 | import pytest 6 | number = 10 7 | def number_game(x): 8 | if x == int(number): 9 | raise ValueError("BOOM! Value Wrong") 10 | 11 | else: 12 | # print("you pass") 13 | pass 14 | 15 | # number_game(0) #you pass 16 | # number_game(10) #ValueError: BOOM! Value Wrong 17 | def test_game1(): 18 | with pytest.raises(ValueError): 19 | number_game(10) 20 | 21 | def test_game2(): 22 | # assert number_game(2) == print("you pass") 23 | assert number_game(2) == None 24 | -------------------------------------------------------------------------------- /pytest/test_pytest_learning_function.py: -------------------------------------------------------------------------------- 1 | ## test_pytest_learning_function.py 2 | 3 | def multiply(x,y): 4 | return x*y 5 | def test1(): 6 | assert 2 == multiply(1,2) 7 | 8 | def test2(): 9 | assert 1 != multiply(1,2) -------------------------------------------------------------------------------- /regular_expression/images/image1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/regular_expression/images/image1.png -------------------------------------------------------------------------------- /regular_expression/images/image10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/regular_expression/images/image10.png -------------------------------------------------------------------------------- /regular_expression/images/image11.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/regular_expression/images/image11.png -------------------------------------------------------------------------------- /regular_expression/images/image12.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/regular_expression/images/image12.PNG -------------------------------------------------------------------------------- /regular_expression/images/image13.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/regular_expression/images/image13.PNG -------------------------------------------------------------------------------- /regular_expression/images/image2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/regular_expression/images/image2.png -------------------------------------------------------------------------------- /regular_expression/images/image3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/regular_expression/images/image3.png -------------------------------------------------------------------------------- /regular_expression/images/image4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/regular_expression/images/image4.png -------------------------------------------------------------------------------- /regular_expression/images/image5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/regular_expression/images/image5.png -------------------------------------------------------------------------------- /regular_expression/images/image6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/regular_expression/images/image6.png -------------------------------------------------------------------------------- /regular_expression/images/image7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/regular_expression/images/image7.png -------------------------------------------------------------------------------- /regular_expression/images/image8.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/regular_expression/images/image8.png -------------------------------------------------------------------------------- /regular_expression/images/image9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/regular_expression/images/image9.png -------------------------------------------------------------------------------- /regular_expression/表格.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/regular_expression/表格.pptx -------------------------------------------------------------------------------- /searchsorted/.ipynb_checkpoints/searchsorted-checkpoint.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [], 3 | "metadata": {}, 4 | "nbformat": 4, 5 | "nbformat_minor": 4 6 | } 7 | -------------------------------------------------------------------------------- /searchsorted/NumPy-Searchsorted-Method.md: -------------------------------------------------------------------------------- 1 | # 給自己的Python小筆記 - NumPy中的 searchsorted用法 - 實作數據装箱(分組) 2 | 3 | 4 | 5 | 6 | 7 | ## 1. Searchsorted 函數 8 | 9 | 10 | 11 | ``` 12 | np.searchsorted(a, v, side='left', sorter = None) 13 | ``` 14 | 15 | 說明: 於數組a中插入數組v,但不實際插人,而是返回一個索引列表,表示V中的元素應該插在a中哪個位置 16 | 17 | **重要提醒: ** 預設的狀況下sorter=None,也就是a數組要為升序數組,也就是要排好從小到大的數組 18 | 19 | 20 | 21 | 22 | 23 | ## 2. 參數 24 | 25 | 26 | 27 | 28 | |參數|傳入|說明| 29 | |---|---| 30 | |a|1-D array_like|輸入數組(Input Array),條件: 當sorted = None時,a必須是升序數組;否則,sorted 不可以為None,存放a中元素的索引(index),用來反映a數組的升序排列方式| 31 | |v|array_like|用來插入a數組的值,可以是單個元素 、list或是array| 32 | |side|{'left', 'right'}, optional(可選)| 33 | |查詢的方向: 當side = 'left時,會返回第一個符合條件的元素位置; 當side = 'right時, 會返回最後一固符合條件的元素位置,如果都沒有符合的索引,會返回0或N(a的長度),0表示插入的值比輸人數组的最小值還小,N表示插入的值比輸人數組的最大值還大| 34 | |sorter|1-D array_like, optional(可選)|存儲a數组中元素的index,index對應元素升序| 35 | 36 | 37 | 38 | 39 | 40 | ## 3. 實作 41 | 42 | 43 | 44 | ### 構建輸入數組 45 | ```Python 46 | ## 導人NumPy套件 47 | import numpy as np 48 | 49 | ## 構建一個NumPy 數組 50 | x = np.array([0,2,8,10,14,17,19,25,29,32,36,58]) 51 | x 52 | ``` 53 | 54 | **執行結果** 55 | 56 | ``` 57 | array([ 0, 2, 8, 10, 14, 17, 19, 25, 29, 32, 36, 58]) 58 | ``` 59 | 60 | 61 | 62 | 63 | 64 | ### 1. 插人單個元素 65 | 66 | 67 | 68 | 69 | #### A. 插入輸入數組中沒有的元素(介於最大與最小值之間的數) 70 | ```Python 71 | ## 插入單個元素 72 | ind1 = np.searchsorted(x, 28) 73 | print ('Insert 28: ', ind1) 74 | 75 | ## 設定side=left 76 | ind2 = np.searchsorted(x, 28, side = 'left') 77 | print ('Insert 28 and set side = left: ', ind2) 78 | 79 | ## 設定side = right 80 | ind3 = np.searchsorted(x, 28, side = 'right') 81 | print('Insert 28 and set side = right: ', ind3) 82 | ``` 83 | 84 | **執行結果** 85 | 86 | ``` 87 | Insert 28: 8 88 | Insert 28 and set side = left: 8 89 | Insert 28 and set side = right: 8 90 | ``` 91 | 92 | 93 | 94 | #### B. 插入比輸入數組最小值更小的元素 95 | 96 | 97 | 98 | ```Python 99 | ## 插入比輸人數組的最小值更小的元素 100 | 101 | ## 設定side = left 102 | ind1 = np.searchsorted(x, -2, side = 'left') 103 | print('Insert 28 and set side = left: ', ind1) 104 | 105 | ## 設定side = right 106 | ind2 = np.searchsorted (x, -2, side = 'right') 107 | print('Insert 28 and set side = right: ', ind2) 108 | ``` 109 | 110 | **執行結果** 111 | 112 | ``` 113 | Insert 28 and set side = left: 0 114 | Insert 28 and set side = right: 0 115 | ``` 116 | 117 | 118 | 119 | 120 | 121 | #### C. 插入比輸入數組最大值更大的元素 122 | 123 | 124 | 125 | ```Python 126 | ## 插入比輸入數组最大值更大的元素 127 | ## 設定side = left 128 | ind1 = np.searchsorted (x, 99, side = 'left') 129 | print ('Insert 28 and set side = left: ', ind1) 130 | 131 | ## 設定side = right 132 | ind2 = np.searchsorted(x, 99, side = 'right') 133 | print('Insert 28 and set side = right: ', ind2) 134 | ``` 135 | 136 | **執行結果** 137 | 138 | ``` 139 | Insert 28 and set side = left: 12 140 | Insert 28 and set side = right: 12 141 | ``` 142 | 143 | 144 | 145 | 146 | 147 | #### D. 插入值跟輸入數組裡面的元素相等 148 | 149 | 150 | 151 | ```Python 152 | ## 播入信跟輸人數组裡面的元素相等 153 | ## 設定side=left 154 | ind1 = np.searchsorted(x, 2, side = 'left') 155 | print ('Insert 28 and set side = left: ', ind1) 156 | 157 | ## 設定side = right 158 | ind2 = np.searchsorted(x, 2, side = 'right') 159 | print('Insert 28 and set side = right: ', ind2) 160 | 161 | 162 | 163 | ## 當插人值跟輸入數組裡面的元素相等, side -'left'和s ide = 'right'結果是不一樣的 164 | ## 1.side = left: 會返回與相同元素一樣的位置 165 | ## 2.side=right:會返回相同元素的下一個位置 166 | ``` 167 | 168 | **執行結果** 169 | 170 | ``` 171 | Insert 28 and set side = left: 1 172 | Insert 28 and set side = right: 2 173 | ``` 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | **結果:當插入值跟输入數組裡面的元素相等,side = 'left'和side = 'right'結果是不一樣的** 182 | 183 | 1. side="left": 會返回與相同元素一樣的位置 184 | 185 | 2. side="right": 會返回相同元素的下個位置 186 | 187 | 188 | 189 | 190 | 191 | ### 2. 插入數組 192 | 193 | ```Python 194 | ## 插入值為一個數組 195 | ## 設定side = left 196 | ind1 = np.searchsorted(x, [-2,3,8,9,26,28,58,66], side = 'left') 197 | print ('Insert 28 and set side = left: ', ind1) 198 | 199 | ## 設定side = right 200 | ind2 = np.searchsorted(x, [-2,3,8,9, 26, 28, 58,66], side = 'right') 201 | print('Insert 28 and set side = right:', ind2) 202 | ``` 203 | 204 | **執行結果** 205 | 206 | ``` 207 | Insert 28 and set side = left: [ 0 2 2 3 8 8 11 12] 208 | Insert 28 and set side = right: [ 0 2 3 3 8 8 12 12] 209 | ``` 210 | 211 | 212 | 213 | 結果: 返回一個數組 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | ### 3. 當輸人數據沒有排好序(升序)的狀況 222 | 223 | 224 | **解決方法:** 這時候就要設定sorter,透過np.argsort()找到沒有排好序的翰人數據的正確(升序)索引數組,再带進sorter就可以解決了 225 | 226 | 227 | ```Python 228 | ## 當輸入數組不是升序的狀況 229 | ## 隐機排列x數組 230 | np.random.shuffle(x) 231 | print ('x = ', x) 232 | 233 | 234 | ## 要先存放x的正確排序索引值 235 | x_sort_index = np.argsort(x) 236 | print('x_sort_index: ', x_sort_index) 237 | 238 | ## 接下來才能執行插人 239 | 240 | ## 設定side = left 241 | ind1 = np.searchsorted (x, [-2,3,8,9,26,28, 58,66], side ='left', sorter = x_sort_index) 242 | print('Insert 28 and set side = left: ', ind1) 243 | 244 | ## 設定side=right 245 | ind2 = np.searchsorted (x, [-2,3,8,9, 26,28, 58, 66], side = 'right', sorter = x_sort_index) 246 | print('Insert 28 and set side right: ', ind2) 247 | ``` 248 | 249 | **執行結果** 250 | 251 | ``` 252 | x = [29 19 10 58 2 17 14 36 25 32 0 8] 253 | x_sort_index: [10 4 11 2 6 5 1 8 0 9 7 3] 254 | Insert 28 and set side = left: [ 0 2 2 3 8 8 11 12] 255 | Insert 28 and set side right: [ 0 2 3 3 8 8 12 12] 256 | ``` 257 | 258 | 259 | 260 | ## 應用範例:數據裝箱(分組) 261 | 262 | 263 | 264 | + 舉例: 我們有1000 個值,想將它們分別放人各個不同的數組分組中,並快速地找到它們在分組數組中的位置, 此時就可以使用searchsorted()函數找到這些值應該被放人哪個箱子 265 | 266 | 267 | 268 | 269 | 270 | 271 | ```Python 272 | import numpy as np 273 | import matplotlib.pyplot as plt 274 | 275 | ## 隨機產生一個一維並擁有100個標準正態分布的值 276 | np.random.seed(66) 277 | x = np.random.randn(100) 278 | 279 | ## 自定義一個數據分組, 區間-5到5平均取20個數據點,每個區間為一個數據分組 280 | bins = np.linspace (-5, 5, 20) 281 | 282 | 283 | ## counts為x數值落入區間的計數 284 | counts = np.zeros_like(bins) 285 | 286 | ## 使用searchsorted, 來獲得x每個數據點在bins中落人的區間序號 287 | i = np.searchsorted(bins, x) 288 | print('Searchsorted Index: ',i) 289 | 290 | 291 | ## 使用at和add, 對x元素在每個區間的元素個數進行計算 292 | np.add.at(counts, i, 1) 293 | 294 | ## 視覺化 295 | plt.plot(bins, counts, ds = 'steps') 296 | ``` 297 | 298 | **執行結果** 299 | 300 | ![2](images\2.PNG) -------------------------------------------------------------------------------- /searchsorted/images/1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/searchsorted/images/1.PNG -------------------------------------------------------------------------------- /searchsorted/images/2.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/searchsorted/images/2.PNG -------------------------------------------------------------------------------- /selenium/chromedriver.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/selenium/chromedriver.exe -------------------------------------------------------------------------------- /selenium/debug.log: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/selenium/debug.log -------------------------------------------------------------------------------- /selenium/driver/chromedriver.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/selenium/driver/chromedriver.exe -------------------------------------------------------------------------------- /simplehttpserver_learning/__pycache__/httpserver.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/simplehttpserver_learning/__pycache__/httpserver.cpython-37.pyc -------------------------------------------------------------------------------- /simplehttpserver_learning/httpserver.py: -------------------------------------------------------------------------------- 1 | ## http.server.py 2 | 3 | 4 | # -*- coding: utf-8 -*- 5 | import sys 6 | import http.server 7 | from http.server import SimpleHTTPRequestHandler 8 | 9 | HandlerClass = SimpleHTTPRequestHandler 10 | ServerClass = http.server.HTTPServer 11 | Protocol = "HTTP/1.0" 12 | 13 | if sys.argv[1:]: 14 | port = int(sys.argv[1]) 15 | else: 16 | port = 8060 17 | server_address = ('127.0.0.1', port) 18 | 19 | HandlerClass.protocol_version = Protocol 20 | httpd = ServerClass(server_address, HandlerClass) 21 | 22 | sa = httpd.socket.getsockname() 23 | print("Serving HTTP on", sa[0], "port", sa[1], "...") 24 | httpd.serve_forever() 25 | 26 | -------------------------------------------------------------------------------- /simplehttpserver_learning/httpserver_learning.md: -------------------------------------------------------------------------------- 1 | # Coding起來 - Python - 一行指令就能輕鬆建立網頁伺服器 - SimpleHTTPServer套件 - http.server使用教學 2 | 3 | 4 | 5 | 嗨嗨,大家有時候在寫網頁前端或簡單的互動視覺化圖時,可能都會想用網頁伺服器來預覽成品放到網頁上的感覺,但有時候只是想簡單檢視一下結果,卻要花上很多時間安裝完整的伺服器(ex.Apache),或是撰寫nodejs來開啟Local Server,今天就來跟大家介紹一個我今天無意間看到的一個超實用套件- SimpleHTTPServer,它幫助我們省下非常多的時間,只要一行指令輕鬆就能幫助我們開啟Local Server,建立臨時的網頁 6 | 7 | 8 | 9 | 10 | 11 | ## 為什麼要使用SimpleHTTPServer? 12 | 13 | + 它幫助我們快速地將Local端任何目錄底下的資料以網頁的形式分享到網路上,除了可以幫助我們預覽一些工作成果,像是網頁前端、互動視覺畫圖等等,也可以幫助將資料分享於區域網路(Local Network)之中,我們就能快速地展示結果給身邊的人用自己的網路設備觀看 14 | 15 | 16 | 17 | + 使用SimpleHTTPServer的方法,只要擁有Python環境,並只要一行指令就能建立簡單地網頁伺服器 18 | 19 | 20 | 21 | 22 | 23 | ## 環境建置 24 | 25 | 26 | 27 | 1. 安裝Python3,並添加到環境變數之中,就能使用命令提示字元(cmd)來執行操作 28 | 29 | 2. 直接安裝Anaconda,就能直接使用Anaconda Prompt來執行操作 30 | 31 | 32 | 33 | **提醒: 我這邊使用的SimpleHTTPServer套件是Python3版本的喔,所以指令會與Python2不同** 34 | 35 | ``` 36 | Python3指令: python -m http.server 37 | Python2指令: python -m SimpleHTTPServer 38 | ``` 39 | 40 | 41 | 42 | 43 | 44 | ## 如何使用SimpleHTTPServer? 45 | 46 | 47 | 48 | #### Step1: 49 | 50 | 選定欲開方的目錄資料夾,並開啟命令提示字元(cmd)或任何可以使用Python的指令工具(ex. Anaconda Prompt),我這邊使用Anaconda Prompt 來示範,開啟後切換(cd)到欲開放的目錄資料夾內(ex. cd C:\Users\user\Desktop\Learn-Python-\simplehttpserver_learning)![image1](images/image1.PNG) 51 | 52 | 53 | 54 | #### Step2: 55 | 56 | 開啟Local Server, 在Anaconda Prompt中接著下python -m http.server指令 57 | 58 | ``` 59 | python -m http.server 60 | ``` 61 | 62 | ![image2](images\image2.PNG) 63 | 64 | 65 | 66 | #### Step3: 67 | 68 | 打開瀏覽器,並輸入 69 | 70 | 1. 自己觀看的網址: http://127.0.0.1:8000/![image3](images\image3.PNG) 71 | 72 | 2. 分享給別的網址: 73 | + 找到自己的IP位置,並在後面加上:8000,就可以囉 74 | 75 | ex. http://192.168.31.214:8000/ 76 | 77 | ![image4](images\image4.PNG) 78 | 79 | **補充: 如何找自己的IP位置? 在cmd中,輸入ipconfig指令,就會看到了** 80 | 81 | 82 | 83 | **這樣就算完成囉,是不是非常輕鬆呀,這樣大家就能看到你分享的檔案囉!!** 84 | 85 | 86 | 87 | ## 補充: 如果想修改Port呢? 88 | 89 | SimpleHTTPServer模組預設的port為8000,也就是上面我們IP位置後面指定的Port,像是http://127.0.0.1:8000/,後面的8000就是Port,如果想要指定不同的Port,非常簡單喔,只要在指令後面加上指定的Port就好,想是我想要將Port改變為8080,就輸入以下指令 90 | 91 | ``` 92 | python -m http.server 8080 93 | ``` 94 | 95 | ![image5](images\image5.PNG) 96 | 97 | 98 | 99 | ## 補充: 自行寫一個Python程式來開啟 100 | 101 | 預設情況下,這個套件會傾聽所有的網路位置,如果想要只傾聽local端的位址,就要自行寫一個Python程式來執行囉 102 | 103 | 104 | 105 | **範例1 : 這是我在網路上找尋大家的文章,所使用的範例程式** 106 | 107 | ```Python 108 | ## http.server.py 109 | 110 | 111 | # -*- coding: utf-8 -*- 112 | import sys 113 | import http.server 114 | from http.server import SimpleHTTPRequestHandler 115 | 116 | HandlerClass = SimpleHTTPRequestHandler 117 | ServerClass = http.server.HTTPServer 118 | Protocol = "HTTP/1.0" 119 | 120 | if sys.argv[1:]: 121 | port = int(sys.argv[1]) 122 | else: 123 | port = 8000 124 | server_address = ('127.0.0.1', port) 125 | 126 | HandlerClass.protocol_version = Protocol 127 | httpd = ServerClass(server_address, HandlerClass) 128 | 129 | sa = httpd.socket.getsockname() 130 | print("Serving HTTP on", sa[0], "port", sa[1], "...") 131 | httpd.serve_forever() 132 | 133 | ``` 134 | 135 | 136 | 137 | **範例2: 這邊檢安教大家如何修改預設的port,只要將程式檔裡的port改變(ex. port = 8060),再執行這個程式檔,就可以囉!!** 138 | 139 | ```Python 140 | ## http.server.py 141 | 142 | 143 | # -*- coding: utf-8 -*- 144 | import sys 145 | import http.server 146 | from http.server import SimpleHTTPRequestHandler 147 | 148 | HandlerClass = SimpleHTTPRequestHandler 149 | ServerClass = http.server.HTTPServer 150 | Protocol = "HTTP/1.0" 151 | 152 | if sys.argv[1:]: 153 | port = int(sys.argv[1]) 154 | else: 155 | port = 8060 156 | server_address = ('127.0.0.1', port) 157 | 158 | HandlerClass.protocol_version = Protocol 159 | httpd = ServerClass(server_address, HandlerClass) 160 | 161 | sa = httpd.socket.getsockname() 162 | print("Serving HTTP on", sa[0], "port", sa[1], "...") 163 | httpd.serve_forever() 164 | 165 | ``` 166 | 167 | 168 | 169 | 接著執行Python檔,開啟Local Server,一樣輸入指令: 170 | 171 | ``` 172 | python -m httpserver 173 | ``` 174 | 175 | ![image6](images\image6.PNG) 176 | 177 | 結果就會發現,預設的Port改變成8060囉 178 | 179 | 180 | 181 | 182 | 183 | **希望這次也有幫助到大家~~** 184 | 185 | 186 | 187 | ## Reference: 188 | 189 | 190 | 191 | https://blog.gtwang.org/web-development/python-simplehttpserver-web-server/ 192 | 193 | https://www.afternerd.com/blog/python-http-server/ 194 | 195 | https://shengyu7697.github.io/blog/2019/11/27/Python-simple-web-server/ 196 | 197 | https://www.linuxjournal.com/content/tech-tip-really-simple-http-server-python 198 | 199 | https://www.itread01.com/content/1547851700.html -------------------------------------------------------------------------------- /simplehttpserver_learning/images/image1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/simplehttpserver_learning/images/image1.PNG -------------------------------------------------------------------------------- /simplehttpserver_learning/images/image2.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/simplehttpserver_learning/images/image2.PNG -------------------------------------------------------------------------------- /simplehttpserver_learning/images/image3.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/simplehttpserver_learning/images/image3.PNG -------------------------------------------------------------------------------- /simplehttpserver_learning/images/image4.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/simplehttpserver_learning/images/image4.PNG -------------------------------------------------------------------------------- /simplehttpserver_learning/images/image5.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/simplehttpserver_learning/images/image5.PNG -------------------------------------------------------------------------------- /simplehttpserver_learning/images/image6.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/simplehttpserver_learning/images/image6.PNG -------------------------------------------------------------------------------- /sphinx/python-project/doc/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = source 9 | BUILDDIR = build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/doctrees/Example.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/sphinx/python-project/doc/build/doctrees/Example.doctree -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/doctrees/environment.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/sphinx/python-project/doc/build/doctrees/environment.pickle -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/doctrees/index.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/sphinx/python-project/doc/build/doctrees/index.doctree -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/.buildinfo: -------------------------------------------------------------------------------- 1 | # Sphinx build info version 1 2 | # This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. 3 | config: 3709c755f2f26260ae0717573af6bb99 4 | tags: 645f666f9bcd5a90fca523b33c5a78b7 5 | -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/Example.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | “Sphinx Example ” dor your documentation — littleturtle 1.0.0 documentation 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 29 | 33 |
34 |
35 | 36 |
37 |

“Sphinx Example ” dor your documentation

38 |

github links

39 |

Here is our description for our code: Little Turtle and it’s home

40 |

41 | Learing Sphinx

42 |
43 | class Example.House(address, name, phone_number)
44 |

House 這個class 有什麼 45 | >>> __init__(self, address, name, phone_number)

46 |
47 |

初始化一個House

48 |
49 |
>>>  move_in(self, amount)
50 |     遷入
51 | 
52 |
53 |
>>>  move_out(self, amount)
54 | 遷出
55 | 
56 |
57 |
>>>  __del__(self)
58 |     毀掉
59 | 
60 |
61 |
62 |

這邊我們建立一個little turle 的家做示範

63 |
64 |
65 |
## 建立一個House(little_turtle_home) 並給予基本資料

little_turtle_home = House(‘any Town any Street’, ‘Turtle’, ‘09xx’) 66 | little_turtle_home.move_in(2) 67 | little_turtle_home.move_in(4) 68 | little_turtle_home.move_in(2) 69 | little_turtle_home.move_out(2) 70 | ## print 出成員人數 71 | print(little_turtle_home.member) 72 | ## 毀掉房子 73 | del little_turtle_home 74 | # print(little_turtle_home) 75 | ##NameError: name ‘little_turtle_home’ is not defined

76 |
77 |
78 |
79 | 80 |
81 |
82 | Example.print_hello()
83 |

哈囉 84 | >>> print(‘hello’)

85 |
86 | 87 |
88 | 89 | 90 |
91 |
92 |
93 | 94 | 98 | 99 | -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/_sources/Example.rst.txt: -------------------------------------------------------------------------------- 1 | "Sphinx Example " dor your **documentation** 2 | ============================================= 3 | 4 | `github links `_ 5 | 6 | Here is our description for our code: Little Turtle and it's home 7 | 8 | 9 | .. automodule:: Example 10 | :members: 11 | :noindex: -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/_sources/index.rst.txt: -------------------------------------------------------------------------------- 1 | .. littleturtle documentation master file, created by 2 | sphinx-quickstart on Wed Jul 1 22:31:30 2020. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to littleturtle's documentation! 7 | ======================================== 8 | 9 | .. toctree:: 10 | :maxdepth: 2 11 | :caption: Contents: 12 | 13 | Example 14 | 15 | Indices and tables 16 | ================== 17 | 18 | * :ref:`genindex` 19 | * :ref:`modindex` 20 | * :ref:`search` 21 | -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/_static/darkmetal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/sphinx/python-project/doc/build/html/_static/darkmetal.png -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/_static/documentation_options.js: -------------------------------------------------------------------------------- 1 | var DOCUMENTATION_OPTIONS = { 2 | URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), 3 | VERSION: '1.0.0', 4 | LANGUAGE: 'None', 5 | COLLAPSE_INDEX: false, 6 | BUILDER: 'html', 7 | FILE_SUFFIX: '.html', 8 | LINK_SUFFIX: '.html', 9 | HAS_SOURCE: true, 10 | SOURCELINK_SUFFIX: '.txt', 11 | NAVIGATION_WITH_KEYS: false 12 | }; -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/_static/file.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/sphinx/python-project/doc/build/html/_static/file.png -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/_static/headerbg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/sphinx/python-project/doc/build/html/_static/headerbg.png -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/_static/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/sphinx/python-project/doc/build/html/_static/logo.png -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/_static/metal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/sphinx/python-project/doc/build/html/_static/metal.png -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/_static/minus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/sphinx/python-project/doc/build/html/_static/minus.png -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/_static/navigation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/sphinx/python-project/doc/build/html/_static/navigation.png -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/_static/plus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/sphinx/python-project/doc/build/html/_static/plus.png -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/_static/print.css: -------------------------------------------------------------------------------- 1 | @media print { 2 | div.header, div.relnav, #toc { display: none; } 3 | #contentwrapper { padding: 0; margin: 0; border: none; } 4 | body { color: black; background-color: white; } 5 | div.footer { border-top: 1px solid #888; color: #888; margin-top: 1cm; } 6 | div.footer a { text-decoration: none; } 7 | } 8 | -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/_static/pygments.css: -------------------------------------------------------------------------------- 1 | .highlight .hll { background-color: #ffffcc } 2 | .highlight { background: #f8f8f8; } 3 | .highlight .c { color: #8f5902; font-style: italic } /* Comment */ 4 | .highlight .err { color: #a40000; border: 1px solid #ef2929 } /* Error */ 5 | .highlight .g { color: #000000 } /* Generic */ 6 | .highlight .k { color: #204a87; font-weight: bold } /* Keyword */ 7 | .highlight .l { color: #000000 } /* Literal */ 8 | .highlight .n { color: #000000 } /* Name */ 9 | .highlight .o { color: #ce5c00; font-weight: bold } /* Operator */ 10 | .highlight .x { color: #000000 } /* Other */ 11 | .highlight .p { color: #000000; font-weight: bold } /* Punctuation */ 12 | .highlight .ch { color: #8f5902; font-style: italic } /* Comment.Hashbang */ 13 | .highlight .cm { color: #8f5902; font-style: italic } /* Comment.Multiline */ 14 | .highlight .cp { color: #8f5902; font-style: italic } /* Comment.Preproc */ 15 | .highlight .cpf { color: #8f5902; font-style: italic } /* Comment.PreprocFile */ 16 | .highlight .c1 { color: #8f5902; font-style: italic } /* Comment.Single */ 17 | .highlight .cs { color: #8f5902; font-style: italic } /* Comment.Special */ 18 | .highlight .gd { color: #a40000 } /* Generic.Deleted */ 19 | .highlight .ge { color: #000000; font-style: italic } /* Generic.Emph */ 20 | .highlight .gr { color: #ef2929 } /* Generic.Error */ 21 | .highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */ 22 | .highlight .gi { color: #00A000 } /* Generic.Inserted */ 23 | .highlight .go { color: #000000; font-style: italic } /* Generic.Output */ 24 | .highlight .gp { color: #8f5902 } /* Generic.Prompt */ 25 | .highlight .gs { color: #000000; font-weight: bold } /* Generic.Strong */ 26 | .highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ 27 | .highlight .gt { color: #a40000; font-weight: bold } /* Generic.Traceback */ 28 | .highlight .kc { color: #204a87; font-weight: bold } /* Keyword.Constant */ 29 | .highlight .kd { color: #204a87; font-weight: bold } /* Keyword.Declaration */ 30 | .highlight .kn { color: #204a87; font-weight: bold } /* Keyword.Namespace */ 31 | .highlight .kp { color: #204a87; font-weight: bold } /* Keyword.Pseudo */ 32 | .highlight .kr { color: #204a87; font-weight: bold } /* Keyword.Reserved */ 33 | .highlight .kt { color: #204a87; font-weight: bold } /* Keyword.Type */ 34 | .highlight .ld { color: #000000 } /* Literal.Date */ 35 | .highlight .m { color: #0000cf; font-weight: bold } /* Literal.Number */ 36 | .highlight .s { color: #4e9a06 } /* Literal.String */ 37 | .highlight .na { color: #c4a000 } /* Name.Attribute */ 38 | .highlight .nb { color: #204a87 } /* Name.Builtin */ 39 | .highlight .nc { color: #000000 } /* Name.Class */ 40 | .highlight .no { color: #000000 } /* Name.Constant */ 41 | .highlight .nd { color: #5c35cc; font-weight: bold } /* Name.Decorator */ 42 | .highlight .ni { color: #ce5c00 } /* Name.Entity */ 43 | .highlight .ne { color: #cc0000; font-weight: bold } /* Name.Exception */ 44 | .highlight .nf { color: #000000 } /* Name.Function */ 45 | .highlight .nl { color: #f57900 } /* Name.Label */ 46 | .highlight .nn { color: #000000 } /* Name.Namespace */ 47 | .highlight .nx { color: #000000 } /* Name.Other */ 48 | .highlight .py { color: #000000 } /* Name.Property */ 49 | .highlight .nt { color: #204a87; font-weight: bold } /* Name.Tag */ 50 | .highlight .nv { color: #000000 } /* Name.Variable */ 51 | .highlight .ow { color: #204a87; font-weight: bold } /* Operator.Word */ 52 | .highlight .w { color: #f8f8f8; text-decoration: underline } /* Text.Whitespace */ 53 | .highlight .mb { color: #0000cf; font-weight: bold } /* Literal.Number.Bin */ 54 | .highlight .mf { color: #0000cf; font-weight: bold } /* Literal.Number.Float */ 55 | .highlight .mh { color: #0000cf; font-weight: bold } /* Literal.Number.Hex */ 56 | .highlight .mi { color: #0000cf; font-weight: bold } /* Literal.Number.Integer */ 57 | .highlight .mo { color: #0000cf; font-weight: bold } /* Literal.Number.Oct */ 58 | .highlight .sa { color: #4e9a06 } /* Literal.String.Affix */ 59 | .highlight .sb { color: #4e9a06 } /* Literal.String.Backtick */ 60 | .highlight .sc { color: #4e9a06 } /* Literal.String.Char */ 61 | .highlight .dl { color: #4e9a06 } /* Literal.String.Delimiter */ 62 | .highlight .sd { color: #8f5902; font-style: italic } /* Literal.String.Doc */ 63 | .highlight .s2 { color: #4e9a06 } /* Literal.String.Double */ 64 | .highlight .se { color: #4e9a06 } /* Literal.String.Escape */ 65 | .highlight .sh { color: #4e9a06 } /* Literal.String.Heredoc */ 66 | .highlight .si { color: #4e9a06 } /* Literal.String.Interpol */ 67 | .highlight .sx { color: #4e9a06 } /* Literal.String.Other */ 68 | .highlight .sr { color: #4e9a06 } /* Literal.String.Regex */ 69 | .highlight .s1 { color: #4e9a06 } /* Literal.String.Single */ 70 | .highlight .ss { color: #4e9a06 } /* Literal.String.Symbol */ 71 | .highlight .bp { color: #3465a4 } /* Name.Builtin.Pseudo */ 72 | .highlight .fm { color: #000000 } /* Name.Function.Magic */ 73 | .highlight .vc { color: #000000 } /* Name.Variable.Class */ 74 | .highlight .vg { color: #000000 } /* Name.Variable.Global */ 75 | .highlight .vi { color: #000000 } /* Name.Variable.Instance */ 76 | .highlight .vm { color: #000000 } /* Name.Variable.Magic */ 77 | .highlight .il { color: #0000cf; font-weight: bold } /* Literal.Number.Integer.Long */ -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/_static/theme_extras.js: -------------------------------------------------------------------------------- 1 | $(function() { 2 | 3 | var 4 | toc = $('#toc').show(), 5 | items = $('#toc > ul').hide(); 6 | 7 | $('#toc h3') 8 | .click(function() { 9 | if (items.is(':visible')) { 10 | items.animate({ 11 | height: 'hide', 12 | opacity: 'hide' 13 | }, 300, function() { 14 | toc.removeClass('expandedtoc'); 15 | }); 16 | } 17 | else { 18 | items.animate({ 19 | height: 'show', 20 | opacity: 'show' 21 | }, 400); 22 | toc.addClass('expandedtoc'); 23 | } 24 | }); 25 | 26 | }); 27 | -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/_static/watermark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/sphinx/python-project/doc/build/html/_static/watermark.png -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/_static/watermark_blur.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/sphinx/python-project/doc/build/html/_static/watermark_blur.png -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/genindex.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Index — littleturtle 1.0.0 documentation 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 |
25 |

Index

27 |
28 | 31 |
32 |
33 | 34 | 35 |

Index

36 | 37 |
38 | 39 |
40 | 41 | 42 |
43 |
44 |
45 | 46 | 50 | 51 | -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Welcome to littleturtle’s documentation! — littleturtle 1.0.0 documentation 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 29 | 33 |
34 | 42 |
43 | 44 |
45 |

Welcome to littleturtle’s documentation!

46 |
47 |

Contents:

48 | 51 |
52 |
53 |
54 |

Indices and tables

55 | 60 |
61 | 62 | 63 |
64 |
65 |
66 | 67 | 71 | 72 | -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/objects.inv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/sphinx/python-project/doc/build/html/objects.inv -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/search.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Search — littleturtle 1.0.0 documentation 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 |
30 |

Search

32 |
33 | 36 |
37 |
38 | 39 |

Search

40 |
41 | 42 |

43 | Please activate JavaScript to enable the search 44 | functionality. 45 |

46 |
47 |

48 | Searching for multiple words only shows matches that contain 49 | all words. 50 |

51 |
52 | 53 | 54 | 55 |
56 | 57 |
58 | 59 |
60 | 61 |
62 |
63 |
64 | 65 | 69 | 70 | -------------------------------------------------------------------------------- /sphinx/python-project/doc/build/html/searchindex.js: -------------------------------------------------------------------------------- 1 | Search.setIndex({docnames:["Example","index"],envversion:{"sphinx.domains.c":2,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":3,"sphinx.domains.index":1,"sphinx.domains.javascript":2,"sphinx.domains.math":2,"sphinx.domains.python":2,"sphinx.domains.rst":2,"sphinx.domains.std":1,sphinx:56},filenames:["Example.rst","index.rst"],objects:{},objnames:{},objtypes:{},terms:{"09xx":0,"\u4e26\u7d66\u4e88\u57fa\u672c\u8cc7\u6599":0,"\u51fa\u6210\u54e1\u4eba\u6578":0,"\u521d\u59cb\u5316\u4e00\u500bhous":0,"\u54c8\u56c9":0,"\u5efa\u7acb\u4e00\u500bhous":0,"\u6709\u4ec0\u9ebc":0,"\u6bc0\u6389":0,"\u6bc0\u6389\u623f\u5b50":0,"\u7684\u5bb6\u505a\u793a\u7bc4":0,"\u9019\u500bclass":0,"\u9019\u908a\u6211\u5011\u5efa\u7acb\u4e00\u500blittl":0,"\u9077\u5165":0,"\u9077\u51fa":0,"class":0,__del__:0,__init__:0,address:0,amount:0,ani:0,chwang12341:[],code:0,com:[],content:1,defin:0,del:0,descript:0,dor:1,exampl:1,github:0,hello:0,here:0,home:0,hous:0,http:[],index:1,lear:0,learn:[],link:0,littl:0,little_turtle_hom:0,member:0,modul:1,move_in:0,move_out:0,name:0,nameerror:0,our:0,page:1,phone_numb:0,print:0,print_hello:0,python:[],search:1,self:0,sphinx:1,street:0,town:0,turl:0,turtl:0,your:1},titles:["\u201cSphinx Example \u201d dor your documentation","Welcome to littleturtle\u2019s documentation!"],titleterms:{document:[0,1],dor:0,exampl:0,indic:1,littleturtl:1,sphinx:0,tabl:1,welcom:1,your:0}}) -------------------------------------------------------------------------------- /sphinx/python-project/doc/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=source 11 | set BUILDDIR=build 12 | 13 | if "%1" == "" goto help 14 | 15 | %SPHINXBUILD% >NUL 2>NUL 16 | if errorlevel 9009 ( 17 | echo. 18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 19 | echo.installed, then set the SPHINXBUILD environment variable to point 20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 21 | echo.may add the Sphinx directory to PATH. 22 | echo. 23 | echo.If you don't have Sphinx installed, grab it from 24 | echo.http://sphinx-doc.org/ 25 | exit /b 1 26 | ) 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /sphinx/python-project/doc/source/Example.rst: -------------------------------------------------------------------------------- 1 | "Sphinx Example " dor your **documentation** 2 | ============================================= 3 | 4 | `github links `_ 5 | 6 | Here is our description for our code: Little Turtle and it's home 7 | 8 | 9 | .. automodule:: Example 10 | :members: 11 | :noindex: -------------------------------------------------------------------------------- /sphinx/python-project/doc/source/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # This file only contains a selection of the most common options. For a full 4 | # list see the documentation: 5 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 6 | 7 | # -- Path setup -------------------------------------------------------------- 8 | 9 | # If extensions (or modules to document with autodoc) are in another directory, 10 | # add these directories to sys.path here. If the directory is relative to the 11 | # documentation root, use os.path.abspath to make it absolute, like shown here. 12 | # 13 | import os 14 | import sys 15 | sys.path.insert(0, os.path.abspath('../../src')) 16 | 17 | 18 | # -- Project information ----------------------------------------------------- 19 | 20 | project = 'littleturtle' 21 | copyright = '2020, Shane' 22 | author = 'Shane' 23 | 24 | # The full version, including alpha/beta/rc tags 25 | release = '1.0.0' 26 | 27 | 28 | # -- General configuration --------------------------------------------------- 29 | 30 | # Add any Sphinx extension module names here, as strings. They can be 31 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 32 | # ones. 33 | extensions = ['sphinx.ext.autodoc'] 34 | 35 | # Add any paths that contain templates here, relative to this directory. 36 | templates_path = ['_templates'] 37 | 38 | # List of patterns, relative to source directory, that match files and 39 | # directories to ignore when looking for source files. 40 | # This pattern also affects html_static_path and html_extra_path. 41 | exclude_patterns = [] 42 | 43 | 44 | # -- Options for HTML output ------------------------------------------------- 45 | 46 | # The theme to use for HTML and HTML Help pages. See the documentation for 47 | # a list of builtin themes. 48 | # 49 | html_theme = 'scrolls' 50 | 51 | # Add any paths that contain custom static files (such as style sheets) here, 52 | # relative to this directory. They are copied after the builtin static files, 53 | # so a file named "default.css" will overwrite the builtin "default.css". 54 | html_static_path = ['_static'] -------------------------------------------------------------------------------- /sphinx/python-project/doc/source/index.rst: -------------------------------------------------------------------------------- 1 | .. littleturtle documentation master file, created by 2 | sphinx-quickstart on Wed Jul 1 22:31:30 2020. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to littleturtle's documentation! 7 | ======================================== 8 | 9 | .. toctree:: 10 | :maxdepth: 2 11 | :caption: Contents: 12 | 13 | Example 14 | 15 | Indices and tables 16 | ================== 17 | 18 | * :ref:`genindex` 19 | * :ref:`modindex` 20 | * :ref:`search` 21 | -------------------------------------------------------------------------------- /sphinx/python-project/src/Example.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | ## Example.py 3 | """ 4 | .. centered:: Learing Sphinx 5 | .. codeauthor:: Shane 6 | """ 7 | ## 建立一個House 8 | class House: 9 | 10 | """ House 這個class 有什麼 11 | >>> __init__(self, address, name, phone_number) 12 | 初始化一個House 13 | >>> move_in(self, amount) 14 | 遷入 15 | 16 | >>> move_out(self, amount) 17 | 遷出 18 | >>> __del__(self) 19 | 毀掉 20 | 21 | 22 | 這邊我們建立一個little turle 的家做示範 23 | ## 建立一個House(little_turtle_home) 並給予基本資料 24 | little_turtle_home = House('any Town any Street', 'Turtle', '09xx') 25 | little_turtle_home.move_in(2) 26 | little_turtle_home.move_in(4) 27 | little_turtle_home.move_in(2) 28 | little_turtle_home.move_out(2) 29 | ## print 出成員人數 30 | print(little_turtle_home.member) 31 | ## 毀掉房子 32 | del little_turtle_home 33 | # print(little_turtle_home) 34 | ##NameError: name 'little_turtle_home' is not defined 35 | """ 36 | def __init__(self, address, name, phone_number): 37 | self.address = address 38 | self.name = name 39 | self.phone_number = phone_number 40 | self.member = 0 41 | 42 | ## 遷入的fucntion 43 | def move_in(self, amount): 44 | 45 | if amount < 0: 46 | raise ValueError("Amazing: people amount can't be negative") 47 | else: 48 | self.member += amount 49 | 50 | ## 遷出的function 51 | def move_out(self, amount): 52 | 53 | if amount > self.member: 54 | raise ValueError('exceed the amount of people here') 55 | else: 56 | self.member -= amount 57 | ## 破壞房子的方法 58 | def __del__(self): 59 | return "destroy the house" 60 | ## 建立一個House(little_turtle_home) 並給予基本資料 61 | little_turtle_home = House('any Town any Street', 'Turtle', '09xx') 62 | little_turtle_home.move_in(2) 63 | little_turtle_home.move_in(4) 64 | little_turtle_home.move_in(2) 65 | little_turtle_home.move_out(2) 66 | ## print 出成員人數 67 | print(little_turtle_home.member) 68 | ## 毀掉房子 69 | del little_turtle_home 70 | # print(little_turtle_home) 71 | ##NameError: name 'little_turtle_home' is not defined 72 | def print_hello(): 73 | """ 74 | 哈囉 75 | >>> print('hello') 76 | 77 | """ 78 | print('Hello') -------------------------------------------------------------------------------- /sphinx/python-project/src/__pycache__/Example.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/sphinx/python-project/src/__pycache__/Example.cpython-37.pyc -------------------------------------------------------------------------------- /variable/Readme.md: -------------------------------------------------------------------------------- 1 | # Python基礎學起來 - 第二集 - 變數的觀念與資料型態 2 | 3 | 當我們在分享一個故事或一個事情時,為了不想每次都講全名,因為講起來很繞口也很累,所以我們會用某A、B同學、同事C或是朋友D來替代對方的名稱,這個時候其實這個替代的名稱就像是變數,而因為我們替代的是字符串,所以資料型態就會是字符串型態,而當我們的變數是像身高、體重等,就會是數值型態的變數,那就讓我們開始今天的內容吧! 4 | 5 | ## 目錄 6 | 7 | 1. 變數是什麼? 8 | 2. 變數命名規則 9 | 3. 宣告變數 & 記憶體的觀念 10 | 4. 資料型態 11 | 12 | ## 一. 變數是什麼? 13 | 14 | 網路上有非常多大神分享變數的定義,那我將這些定義整理如下面,並加入自己的一些話 15 | 16 | - **內容會改變的數** 17 | 18 | 舉例來說這次我故事中用到的A先生與我下一次我故事中的A先生可能換人了,所以它的內容被我改變了,就稱為變數,像是在數學上我們也很常用x, y, z來替代一些數值,然後老師可能要我們在了解x的情況下算出y跟z 19 | 20 | - **可以自行命名且用來儲存資料的一個名稱** 21 | 22 | 我們可以想像是一個盒子,盒子的名稱由我們自己命名,且裡面的東西也是由我們決定,我們可以在裡面放一段話,放一個名字或是放一些數字等 23 | 24 | - **方便我們在寫程式中去使用存在記憶體中的值而自行命名改用的名稱** 25 | 26 | 這邊像是開頭我們提到的,當我們在寫程式的時候或是說故事的時候,會一直重覆用到一些詞或數字,像是名字,所以我們為了快速且方便,我們會將名字自行改成比較好讀或寫的名稱,像是我把王大明改成A先生等 27 | 28 | ## 二. 變數命名規則 29 | 30 | ### **符合規定的命名包含** 31 | 32 | - 大寫字符: A ~ Z 33 | - 小寫字符: a ~ z 34 | - 數字: 0 ~ 9 35 | - 底線: _ 36 | 37 | > **More: Python還可以用中文字當變數,但因為我們使用變數就是要快,所以比較不常見到用中文當變數** 38 | > 39 | 40 | ![Untitled](images/Untitled.png) 41 | 42 | ### **不能用的命名方式** 43 | 44 | - 數字開頭 45 | 46 | ex. 123a, 967ba8 47 | 48 | - Python 保留字 49 | 50 | 由於下面這些都是Python在執行上會用到的一些方式,所以不適合當成變數名稱使用 51 | 52 | ex. 53 | 54 | | and | as | assert | async | await | 55 | | --- | --- | --- | --- | --- | 56 | | break | def | del | return | try | 57 | | lambda | or | yield | else | finally | 58 | 59 | > 除了上面這些Python還有其它保留字,但因為通常命名也不太會想到這些當變數名稱,所以大家也不用太擔心,真的遇到了就改個名稱就好 60 | > 61 | 62 | > 沒有列到的像是空白鍵、星星符號等,再命名上都會造成程式報錯,所以也不要使用喔 63 | > 64 | 65 | ### 什麼是好的變數名稱 66 | 67 | 其實只要清楚明瞭,讓我們一看到這個變數名稱就知道代表的意義,就是一個好的變數名稱,這邊我從Geo-Python的文章中提取了它對於好的變數名稱定義 68 | 69 | 1. 清晰簡潔 70 | 2. 用英文命名。一般編碼慣例是使用英文來命名變數,因為這是程式設計師之間最常見的共同語言。因此,應避免使用像muuttuja這樣的變數名稱。 71 | 3. 變數名稱不要包含特殊字符。Python支持透過程式中給出的各種編碼選項使用特殊字符。但是,在某些情況下,使用類似於lämpötila的變數名稱可能會引起編碼問題。為了安全起見,最好遵循標準的可打印ASCII字符集。 72 | 4. 不要與任何Python關鍵字( Python 保留字)衝突,如for、True、False、and、if、or、else。這些關鍵字在Python中用於特殊操作,不能當成是變數名稱。 73 | 74 | 資料來源: [https://geo-python.github.io/site/notebooks/L1/gcp-1-variable-naming.html](https://geo-python.github.io/site/notebooks/L1/gcp-1-variable-naming.html) 75 | 76 | ## 三. 宣告變數 & 記憶體觀念 77 | 78 | ### 宣告變數 79 | 80 | 簡單來說其實就是賦值給這個我們命名的變數名稱,會用 = 號來表示 81 | 82 | ex. 83 | 84 | ![Untitled](images/Untitled1.png) 85 | 86 | 過去我們學的數學可能會讓大家以為是x等於2,但在程式中我們應該解釋為我們把2這個數值指派給了x這個我們命名的變數 87 | 88 | 當然我們也可以給變數一段話,一個字,一個字母,一個數值或一個浮點數等 89 | 90 | ![Untitled](images/Untitled2.png) 91 | 92 | ### 記憶體的觀念 93 | 94 | 當我們宣告好變數後,這個變數會被存在電腦的記憶體中,這樣我們後續再調用這個變數的時候,電腦就會幫我們去記憶體中拿取剛剛存進的變數值 95 | 96 | > Python在宣告變數的過程中,並不需要像很多其他語言需要事先定義好資料型態,而是它會**動態的去根據我們宣告給變數的值來調整資料型態**,是不是非常方便啊! 但這樣也等於犧牲掉了一些效能 97 | > 98 | 99 | **舉例來說:** 100 | 101 | 我們為了方便自己找尋相關資料網頁,會把它們存在我的最愛中(記憶體),為了方便往後快速找到它,可能還會幫它命名一個好記的名稱(宣告變數),之後當我們需要這筆資料的時候,再到我的最愛中找尋對應的名稱,點進後即可取得我們要的資料網頁 102 | 103 | 以前面我們設定好的變數來看的話,會像如圖這樣 104 | 105 | ![變數配置記憶體圖.png](images/Untitled3.png) 106 | 107 | ## 四. 資料型態 108 | 109 | 學完怎麼宣告變數後,接下來我們就要來了解我們傳遞給變數的資料型態可以有哪些了 110 | 111 | Python大致上賦予我們的變數四種不同的資料型態: 數值、字符串、布林值、特殊的容器(ex. List、Array, Tuple) 112 | 113 | ### 1. **數值** 114 | 115 | a. **整數: int(Integers)** 116 | 117 | ex. 0,1,2,3,4,5,6…等 118 | 119 | ```python 120 | x = 1 121 | y = 26 122 | z = 999 123 | print(x) 124 | print(y) 125 | print(z) 126 | # 類型檢測 127 | print(type(x), type(y), type(z)) 128 | ``` 129 | 130 | **執行結果** 131 | 132 | ``` 133 | 1 134 | 26 135 | 999 136 | 137 | ``` 138 | 139 | b. **浮點數** 140 | 141 | ex. 1.3, 2.6, 7.92等 142 | 143 | ```python 144 | a = 2.7 145 | b = 9.78 146 | c = 10.967 147 | print(a) 148 | print(b) 149 | print(c) 150 | # 類型檢測 151 | print(type(a), type(b), type(c)) 152 | ``` 153 | 154 | 執行結果 155 | 156 | ``` 157 | 2.7 158 | 9.78 159 | 10.967 160 | 161 | ``` 162 | 163 | ### 2. **字符串** 164 | 165 | **a. 單行文字: str(String)** 166 | 167 | 可以使用**單引號**或**雙引號**: ‘’或”” 168 | 169 | p.s. 我記得沒錯的話,有些程式語言單引號只能用在當只有一個字母的時候 170 | 171 | ```python 172 | # 單行文字 173 | 174 | # 單引號 175 | Name = 'Ken' 176 | # 雙引號 177 | Note = 'Welcome To My Website' 178 | 179 | print(Name) 180 | print(Note) 181 | print("Hello " + Name + ", " + Note) 182 | print(type(Name), type(Note)) 183 | ``` 184 | 185 | 執行結果 186 | 187 | ``` 188 | Ken 189 | Welcome To My Website 190 | Hello Ken, Welcome To My Website 191 | 192 | ``` 193 | 194 | b**. 多行文字:** 195 | 196 | 可以使用**三個雙引號: “”” “””** 197 | 198 | ```python 199 | # 多行文字 200 | 201 | Email = """ 202 | Dear Wang, 203 | Your Product have arrived. 204 | 205 | Best Regards, 206 | Su 207 | """ 208 | 209 | print(Email) 210 | print(type(Email)) 211 | ``` 212 | 213 | **執行結果** 214 | 215 | ``` 216 | Dear Wang, 217 | Your Product have arrived. 218 | 219 | Best Regards, 220 | Su 221 | 222 | 223 | ``` 224 | 225 | ### 3. **布林值 Boolean** 226 | 227 | ```python 228 | ## Boolean 229 | 230 | is_checked = True 231 | 232 | Flag = False 233 | 234 | print(is_checked) 235 | print(Flag) 236 | print(type(is_checked), type(Flag)) 237 | 238 | if is_checked == True: 239 | print("Done") 240 | ``` 241 | 242 | **執行結果** 243 | 244 | ``` 245 | True 246 | False 247 | 248 | Done 249 | ``` 250 | 251 | 1. **容器** 252 | 253 | 可以存放像是List、Array、Tuple等 254 | 255 | ```python 256 | import numpy as np 257 | 258 | # List 259 | score_list = [61, 86, 96.3, 99.8] 260 | name_list = ['Una', 'Tom', 'Ken'] 261 | 262 | # Array 263 | info = np.array([ [1, 3, 5], [2, 4, 6] ]) 264 | 265 | # Tuple 266 | e_tuple = (1,2,3) 267 | 268 | print("Score: ", score_list) 269 | print("Name: ", name_list) 270 | print(info) 271 | print(e_tuple) 272 | print(type(score_list), type(name_list), type(info), type(e_tuple)) 273 | ``` 274 | 275 | **執行結果** 276 | 277 | ``` 278 | Score: [61, 86, 96.3, 99.8] 279 | Name: ['Una', 'Tom', 'Ken'] 280 | [[1 3 5] 281 | [2 4 6]] 282 | (1, 2, 3) 283 | 284 | ``` 285 | 286 | 今天我們把腳正式踏入了這個領域,太有趣了,命名也是一個很大的學問,能夠一目瞭然知道這個變數是做什麼用的,是一件非常不容易的事,下一篇就讓我們來了解怎麼開始建立條件了! 期待下篇大家的閱讀了,感謝! 287 | 288 | ## Reference 289 | 290 | [https://chunyeung.medium.com/給自學者的python教學-4-變數篇ep1-9ac8164aac75](https://chunyeung.medium.com/%E7%B5%A6%E8%87%AA%E5%AD%B8%E8%80%85%E7%9A%84python%E6%95%99%E5%AD%B8-4-%E8%AE%8A%E6%95%B8%E7%AF%87ep1-9ac8164aac75) 291 | 292 | [https://realpython.com/python-variables/](https://realpython.com/python-variables/) 293 | 294 | [https://www.learncodewithmike.com/2019/11/python3-python.html](https://www.learncodewithmike.com/2019/11/python3-python.html) 295 | 296 | [https://steam.oxxostudio.tw/category/python/basic/variable.html](https://steam.oxxostudio.tw/category/python/basic/variable.html) 297 | 298 | [https://tw511.com/a/01/3236.html](https://tw511.com/a/01/3236.html) -------------------------------------------------------------------------------- /variable/images/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/variable/images/.DS_Store -------------------------------------------------------------------------------- /variable/images/Untitled 1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/variable/images/Untitled 1.png -------------------------------------------------------------------------------- /variable/images/Untitled 2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/variable/images/Untitled 2.png -------------------------------------------------------------------------------- /variable/images/Untitled.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/variable/images/Untitled.png -------------------------------------------------------------------------------- /variable/images/Untitled3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/variable/images/Untitled3.png -------------------------------------------------------------------------------- /variable/variable_practice.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "2a4a3623", 6 | "metadata": {}, 7 | "source": [ 8 | "# 整數" 9 | ] 10 | }, 11 | { 12 | "cell_type": "code", 13 | "execution_count": 1, 14 | "id": "0f087bd1", 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "x = 1\n", 19 | "y = 26\n", 20 | "z = 999" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": 3, 26 | "id": "59f906d8", 27 | "metadata": {}, 28 | "outputs": [ 29 | { 30 | "name": "stdout", 31 | "output_type": "stream", 32 | "text": [ 33 | "1\n", 34 | "26\n", 35 | "999\n", 36 | " \n" 37 | ] 38 | } 39 | ], 40 | "source": [ 41 | "print(x)\n", 42 | "print(y)\n", 43 | "print(z)\n", 44 | "# 類型檢測\n", 45 | "print(type(x), type(y), type(z))" 46 | ] 47 | }, 48 | { 49 | "cell_type": "markdown", 50 | "id": "73e3c863", 51 | "metadata": {}, 52 | "source": [ 53 | "# 浮點數" 54 | ] 55 | }, 56 | { 57 | "cell_type": "code", 58 | "execution_count": 4, 59 | "id": "b8480f82", 60 | "metadata": {}, 61 | "outputs": [], 62 | "source": [ 63 | "a = 2.7\n", 64 | "b = 9.78\n", 65 | "c = 10.967" 66 | ] 67 | }, 68 | { 69 | "cell_type": "code", 70 | "execution_count": 5, 71 | "id": "0d31479c", 72 | "metadata": {}, 73 | "outputs": [ 74 | { 75 | "name": "stdout", 76 | "output_type": "stream", 77 | "text": [ 78 | "2.7\n", 79 | "9.78\n", 80 | "10.967\n", 81 | " \n" 82 | ] 83 | } 84 | ], 85 | "source": [ 86 | "print(a)\n", 87 | "print(b)\n", 88 | "print(c)\n", 89 | "# 類型檢測\n", 90 | "print(type(a), type(b), type(c))" 91 | ] 92 | }, 93 | { 94 | "cell_type": "markdown", 95 | "id": "4eb77d11", 96 | "metadata": {}, 97 | "source": [ 98 | "# 字符串" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": 13, 104 | "id": "08c9903c", 105 | "metadata": {}, 106 | "outputs": [], 107 | "source": [ 108 | "# 單行文字\n", 109 | "\n", 110 | "# 單引號\n", 111 | "Name = 'Ken'\n", 112 | "# 雙引號\n", 113 | "Note = 'Welcome To My Website'" 114 | ] 115 | }, 116 | { 117 | "cell_type": "code", 118 | "execution_count": 14, 119 | "id": "9324bd7c", 120 | "metadata": {}, 121 | "outputs": [ 122 | { 123 | "name": "stdout", 124 | "output_type": "stream", 125 | "text": [ 126 | "Ken\n", 127 | "Welcome To My Website\n", 128 | "Hello Ken, Welcome To My Website\n", 129 | " \n" 130 | ] 131 | } 132 | ], 133 | "source": [ 134 | "print(Name)\n", 135 | "print(Note)\n", 136 | "print(\"Hello \" + Name + \", \" + Note)\n", 137 | "print(type(Name), type(Note))" 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": 18, 143 | "id": "e8aa0476", 144 | "metadata": {}, 145 | "outputs": [], 146 | "source": [ 147 | "# 多行文字\n", 148 | "\n", 149 | "Email = \"\"\"\n", 150 | "Dear Wang,\n", 151 | "Your Product have arrived.\n", 152 | "\n", 153 | "Best Regards,\n", 154 | "Su\n", 155 | "\"\"\"" 156 | ] 157 | }, 158 | { 159 | "cell_type": "code", 160 | "execution_count": 19, 161 | "id": "05133d09", 162 | "metadata": {}, 163 | "outputs": [ 164 | { 165 | "name": "stdout", 166 | "output_type": "stream", 167 | "text": [ 168 | "\n", 169 | "Dear Wang,\n", 170 | "Your Product have arrived.\n", 171 | "\n", 172 | "Best Regards,\n", 173 | "Su\n", 174 | "\n", 175 | "\n" 176 | ] 177 | } 178 | ], 179 | "source": [ 180 | "print(Email)\n", 181 | "print(type(Email))" 182 | ] 183 | }, 184 | { 185 | "cell_type": "markdown", 186 | "id": "5f6664df", 187 | "metadata": {}, 188 | "source": [ 189 | "# 布林值 Boolean" 190 | ] 191 | }, 192 | { 193 | "cell_type": "code", 194 | "execution_count": 20, 195 | "id": "b9621058", 196 | "metadata": {}, 197 | "outputs": [], 198 | "source": [ 199 | "## Boolean\n", 200 | "\n", 201 | "is_checked = True\n", 202 | "\n", 203 | "Flag = False" 204 | ] 205 | }, 206 | { 207 | "cell_type": "code", 208 | "execution_count": 22, 209 | "id": "32328109", 210 | "metadata": {}, 211 | "outputs": [ 212 | { 213 | "name": "stdout", 214 | "output_type": "stream", 215 | "text": [ 216 | "True\n", 217 | "False\n", 218 | " \n", 219 | "Done\n" 220 | ] 221 | } 222 | ], 223 | "source": [ 224 | "print(is_checked)\n", 225 | "print(Flag)\n", 226 | "print(type(is_checked), type(Flag))\n", 227 | "\n", 228 | "if is_checked == True:\n", 229 | " print(\"Done\")" 230 | ] 231 | }, 232 | { 233 | "cell_type": "markdown", 234 | "id": "70045e9b", 235 | "metadata": {}, 236 | "source": [ 237 | "# 容器" 238 | ] 239 | }, 240 | { 241 | "cell_type": "code", 242 | "execution_count": 25, 243 | "id": "3b437843", 244 | "metadata": {}, 245 | "outputs": [], 246 | "source": [ 247 | "import numpy as np\n", 248 | "\n", 249 | "# List\n", 250 | "score_list = [61, 86, 96.3, 99.8]\n", 251 | "name_list = ['Una', 'Tom', 'Ken']\n", 252 | "\n", 253 | "# Array\n", 254 | "info = np.array([ [1, 3, 5], [2, 4, 6] ])\n", 255 | "\n", 256 | "# Tuple\n", 257 | "e_tuple = (1,2,3)" 258 | ] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "execution_count": 26, 263 | "id": "a6e6413e", 264 | "metadata": {}, 265 | "outputs": [ 266 | { 267 | "name": "stdout", 268 | "output_type": "stream", 269 | "text": [ 270 | "Score: [61, 86, 96.3, 99.8]\n", 271 | "Name: ['Una', 'Tom', 'Ken']\n", 272 | "[[1 3 5]\n", 273 | " [2 4 6]]\n", 274 | "(1, 2, 3)\n", 275 | " \n" 276 | ] 277 | } 278 | ], 279 | "source": [ 280 | "print(\"Score: \", score_list)\n", 281 | "print(\"Name: \", name_list)\n", 282 | "print(info)\n", 283 | "print(e_tuple)\n", 284 | "print(type(score_list), type(name_list), type(info), type(e_tuple))" 285 | ] 286 | } 287 | ], 288 | "metadata": { 289 | "kernelspec": { 290 | "display_name": "Python 3 (ipykernel)", 291 | "language": "python", 292 | "name": "python3" 293 | }, 294 | "language_info": { 295 | "codemirror_mode": { 296 | "name": "ipython", 297 | "version": 3 298 | }, 299 | "file_extension": ".py", 300 | "mimetype": "text/x-python", 301 | "name": "python", 302 | "nbconvert_exporter": "python", 303 | "pygments_lexer": "ipython3", 304 | "version": "3.10.9" 305 | } 306 | }, 307 | "nbformat": 4, 308 | "nbformat_minor": 5 309 | } 310 | -------------------------------------------------------------------------------- /virtual_environment/Readme.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # 給自己的Python小筆記 - 解決環境套件安裝與版本問題,開始建立一個乾淨的環境 - 如何建立虛擬環境 - env 和 virtualenv 套件教學 - Windows系統 4 | 5 | 6 | 7 | 8 | 9 | **由於過去不同專案的需求電腦裡累積了一堆套件?不清楚哪些專案需要哪些套件?不同專案所使用的套件版本又不同所造成的問題?解決環境套件安裝與版本問題,開始建立一個乾淨的環境** 10 | 11 | 12 | 13 | 14 | 15 | 嗨嗨,由於最近工作老是被問到,這個專案環境需要安装什麼套件?我用你寫的步驟,但是環境一直有問題?我突然意識到很多套件都是我在過去不同專案中所累積安装的,所以突然被問這個專案需要什麼套件,不知道要怎麼回答,總不能把我安装過的套件通通給他xd 每次問題一來,我第一個腦海裡浮現的是,你在說哪個專案,啊我這邊可以,你為什麼不行xd 然後就只能一句一句幫他看,報錯的原因跟解決所需要的套件,所以我決定在往後的專案中,每次開一個新專案,就建立一個新環境來安装套件,這樣就清楚明瞭了,但總不能每次開新專案,就砍掉以前的吧,所以這時候虛擬環境對我來說的重要性就出來了xd 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | ## 1. 虛擬環境是什麼? 24 | 25 | 26 | 27 | + 一種獨立出來的Python執行環境,原理是借助虛擬機docker把一部分的內容獨立出來,稱為容器也就是虛擬環境,我們可以在不同的虛擬環境中下載這個專案需要的套件就好,而每個Python虛擬環境互相不影響 28 | + 建立好後會是一個獨立的資料來,裡面有Python版本和所安装的套件 29 | 30 | 31 | 32 | 33 | 34 | ## 2. 虛擬環境的應用場景 35 | 36 | 37 | 38 | + 在學習的過程中怕安装了一堆有的沒有的套件影響電腦 39 | + 每個專案需要的套件版本不同,一直為不同專案重新安裝案件版本很麻煩,像是專案A需要Python3.6.5,但是專案B需要的則是Python2 40 | + 當被問到這個專案需要什麼套件時,可能會忘記自己安裝了什麼,或因為以前別的專案有安装過所以不知道還需要裝哪些 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | ## 3. Python的虛擬環境套件 50 | 51 | 52 | 53 | ### venv 54 | 55 | Python内建用來管理與建立虛擬環境的套件,不需要額外下載 56 | 57 | 58 | 59 | #### STEP 1: 建立虛擬環境 60 | 61 | command: python-m venv (虛擬環境名稱) 62 | 63 | ``` 64 | python -m venv virtual_env 65 | ``` 66 | 67 | ![image1](images\image1.PNG) 68 | 69 | **系統就會在執行的目錄底下創建一個virtual_env的folder** 70 | 71 | 72 | 73 | #### STEP 2: 開啟虛擬環境 74 | 75 | Command: (虛擬環境資料夾名稱)\Scripts\activate.bat 76 | ``` 77 | virtual_env\Scripts\activate.bat 78 | ``` 79 | 80 | 81 | 當命令提示字元前面出現(virtual_env),像是(virtual_env)(bäse) (資料夾路街),表示成功進入了,就可以開始嗨了!! 82 | 83 | ![image2](images\image2.PNG) 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | #### STEP 3: 退出虛擬環境 92 | 93 | Command: (虛擬環境資料夾名稱)\Scripts\deactivate.bat 94 | ``` 95 | virtual_env\Scripts\deactivate.bat 96 | ``` 97 | 當(virtual env)不見了表示成功退出了 98 | 99 | ![image3](images\image3.PNG) 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | ### virtualenv 108 | 109 | 110 | 111 | 112 | 113 | #### STEP 1: 安裝套件 114 | 115 | ``` 116 | pip install virtualenv 117 | ``` 118 | 119 | 120 | 121 | #### STEP 2: 建立虛擬環境 122 | 123 | command: virtualenv (虛擬環境名稱) 124 | ``` 125 | virtualenv virtual_env_1 126 | ``` 127 | 128 | ![image4](images\image4.PNG) 129 | 130 | 131 | 132 | 133 | 134 | #### STEP 3: 開啟虛擬環境 135 | 136 | 137 | Command: (虛擬環境資料夾名稱)\Scripts lactivate.bat 138 | ``` 139 | virtual_env_1\Scripts\activate.bat 140 | ``` 141 | 142 | 當命令提示字元前面出現(virtual_env_1),像是(virtual_env_1)(base) (安料夾路徑),就表示成功進入了,這樣就可以開始發揮了!!xd 143 | 144 | 145 | 146 | #### STEP 4: 退出虛擬環境 147 | 148 | Command: (虛擬環境的資料夾名稱)\Scripts\deactivate.bat 149 | ``` 150 | virtual_env_1\Scripts\deactivate.bat 151 | ``` 152 | 153 | 154 | 當(virtual_env_1)不見了,表示成功退出了 155 | 156 | **兩個套件步驟幾乎是一樣的,只只差在指令略有不同跟一個要下載套件一個是內建的** 157 | 158 | 159 | 160 | 161 | 162 | ## 4. 補充: 一些管理套件的方法 163 | 164 | 165 | 166 | 我們先進到前面建立的虛擬環境中 167 | 168 | 169 | 170 | 171 | 172 | ### 安裝最新版本的套件 173 | 174 | command: pip install (套件名稱) 175 | ``` 176 | pip install plotly 177 | ``` 178 | 179 | 180 | 181 | ### 安裝指定版本的套件 182 | 183 | command: pip install (套件名稱)==(套件版本) 184 | ``` 185 | pip install xlrd==1.2.0 186 | ``` 187 | 188 | 189 | 190 | ### 把安裝好的套件升級到最新版 191 | 192 | command: pip install --upgrade (套件名稱) 193 | ``` 194 | pip install --upgrade xlrd 195 | ``` 196 | 197 | 198 | 199 | ### 查看當前環境有哪些套件 200 | 201 | ``` 202 | pip list 203 | ``` 204 | 205 | **執行結果** 206 | 207 | ![image5](images\image5.PNG) 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | ### 顯示套件資訊 216 | 217 | command: pip show (套件名稱) 218 | ``` 219 | pip show xlrd 220 | ``` 221 | 222 | **執行結果** 223 | 224 | ![image6](images\image6.PNG) 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | ### 將安裝的套件輸出成一個清單(txt檔) 233 | 234 | command: pip freeze > (套件清單名稱).txt 235 | ``` 236 | pip freeze > requirement.txt 237 | 238 | ## 查看清單內容 - Linux 239 | cat requirement.txt 240 | ## 查看清單內容 - Windows 241 | type requirement.txt 242 | ``` 243 | 244 | **執行結果** 245 | 246 | ![image7](images\image7.PNG) 247 | 248 | 249 | 250 | 251 | 252 | ### 透過這份套件清單,直接下載所需套件 253 | 254 | 255 | 256 | command: pip install -r (套件清單名稱).txt 257 | ``` 258 | pip install -r requirement.txt 259 | ``` 260 | 261 | **執行結果** 262 | 263 | ![image8](images\image8.PNG) 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | ## Reference 274 | 275 | https://docs.python.org/zh-tw/3.9/tutorial/venv.html 276 | 277 | https://blog.csdn.net/godot06/article/details/81079064 278 | -------------------------------------------------------------------------------- /virtual_environment/images/image1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/virtual_environment/images/image1.PNG -------------------------------------------------------------------------------- /virtual_environment/images/image2.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/virtual_environment/images/image2.PNG -------------------------------------------------------------------------------- /virtual_environment/images/image3.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/virtual_environment/images/image3.PNG -------------------------------------------------------------------------------- /virtual_environment/images/image4.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/virtual_environment/images/image4.PNG -------------------------------------------------------------------------------- /virtual_environment/images/image5.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/virtual_environment/images/image5.PNG -------------------------------------------------------------------------------- /virtual_environment/images/image6.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/virtual_environment/images/image6.PNG -------------------------------------------------------------------------------- /virtual_environment/images/image7.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/virtual_environment/images/image7.PNG -------------------------------------------------------------------------------- /virtual_environment/images/image8.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chwang12341/Learn-Python-/48d7189de10c5f64abad2eec2867112ec4e214bd/virtual_environment/images/image8.PNG -------------------------------------------------------------------------------- /werkzeug.security/werkzeug.security_learning.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Created on Mon Jul 6 22:08:55 2020 4 | 5 | @author: user 6 | """ 7 | ## 加密與驗證實作 8 | ## 首先導入我們需要的Packages 9 | from werkzeug.security import generate_password_hash, check_password_hash 10 | 11 | ## 建立一個帳號機制 12 | class Account: 13 | 14 | ## 帳號設置 15 | def __init__(self, name): 16 | self.name = name 17 | 18 | ## 密碼設置,但記得不能讓別人能夠閱讀 19 | @property 20 | def password(password): 21 | assert False, "You can not read password" 22 | 23 | ## 給予密碼 24 | @password.setter 25 | def password(self, password): 26 | ## 產生一組加鹽雜湊加密的產出值 27 | self.password_hash = generate_password_hash(password, method='pbkdf2:sha1', salt_length = 10) 28 | 29 | ## 驗證機制 30 | def verify_password(self, password): 31 | return ('Login Succuess' if check_password_hash(self.password_hash, password) == True else 'Sorry Login failed' ) 32 | 33 | ## 先創個帳號 34 | little_turtle = Account('little_turtle') 35 | ## 確定一下帳號名稱 36 | print(little_turtle.name) #ittle_turtle 37 | ## 設置密碼 38 | little_turtle.password = 'Big1234' 39 | ## 查看密碼: 注意我們不能讓別人查看密碼 40 | # print(little_turtle.password) #AssertionError: You can not read password 41 | ## 驗證密碼 42 | print(little_turtle.verify_password('Small1256')) # Sorry Login failed 登入失敗啦 43 | print(little_turtle.verify_password('Big1234')) # Login Succuess 登入成功 --------------------------------------------------------------------------------