tag:blogger.com,1999:blog-29409718223512020572024-03-14T16:30:07.779+07:00Python 3สอนเขียนโปรแกรมด้วยภาษา Python 3wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.comBlogger703125tag:blogger.com,1999:blog-2940971822351202057.post-50479028458474637222024-01-24T19:04:00.001+07:002024-01-25T13:13:52.311+07:00หนังสือ Python ภาษาไทย ออนไลน์ผลงานนี้ ใช้<a data-from-md="" href="http://creativecommons.org/licenses/by/4.0/" title="http://creativecommons.org/licenses/by/4.0/">สัญญาอนุญาตของครีเอทีฟคอมมอนส์แบบ แสดงที่มา 4.0 International</a><a name='more'></a><div id="rendered-md">
<h2 id="บทนํา">บทนำ</h2>
<p>Python เป็นภาษาเขียนโปรแกรมคอมพิวเตอร์ระดับสูง เป็นหนึ่งในภาษาที่ได้ความนิยมอย่างมากในปัจจุบัน ตั้งแต่วงการไอโอที ปัญญาประดิษฐ์ เว็บ และอื่น ๆ เนื่องจากความยืดหยุ่นของตัวภาษา เขียนได้อย่างรวดเร็ว เชื่อมต่อกับภาษาอื่น ๆ ได้ดี ดังนั้น ผู้เริ่มต้นเขียนโปรแกรม หรือ เขียนโปรแกรมเป็นอยู่แล้ว ควรเรียนรู้และสามารถใช้งานภาษานี้ได้</p>
<h2 id="บทที่-1-เริ่มต้นกับ-python">บทที่ 1 เริ่มต้นกับ python</h2>
<p>Python เป็นภาษาอย่างหนึ่งของคอมพิวเตอร์ มีจุดเด่นคล่อง ๆ ดังนี้</p>
<ul><li>เป็นภาษาที่มี syntax ที่เรียบง่ายและสะอาด สามารถเรียนรู้ได้ง่าย เข้าใจได้ง่าย</li><li>สนับสนุนการเขียนโปรแกรมแบบ OOP</li><li>ทำงานแบบ interpreter</li><li>dynamic code (ภาษาที่ไม่ต้องกำหนด type ในการประกาศตัวแปร)</li></ul>
<p>Python เวชั่นแรกถูกพัฒนาโดย Guido van Rossum พัฒนาขึ้นมาในปี ค.ศ.1991<br />ปัจจุบัน Python ได้ถูกพัฒนาโดย Python Software Foundation<br />ได้เดินทางมาถึง Python 3</p>
<h2 id="เริ่มต้นกับภาษา-python">เริ่มต้นกับภาษา Python</h2>
<p>เให้ผู้อ่านติดตั้ง Python ดังนี้</p>
<ul><li>Windows เข้าไปที่ <a data-from-md="" href="https://www.python.org/download/" title="https://www.python.org/download/">https://www.python.org/download/</a> ให้เลือกดาวน์โหลด รุ่นในสาย Python 3 แล้วเลือกให้ตรงกับสเปคเครื่อง ตัวอย่างเช่น เครื่องผมใช้ Windows 64 Bit ผมต้องเลือก Python 3.4.1<br />Windows X86-64 MSI Installer เมื่อรันหน้าต่างติดตั้งขึ้นมา<br />อย่าลืมเลือก set path ด้วย จะได้ไม่ต้องมาเสียเวลาตั้งค่าภายหลัง<br />โดยทำอย่างนี้ เริ่มต้นด้วยการรันไฟล์ติดตั้งที่โหลดมา<br />เสร็จแล้วกด Next ไปเรื่อย ๆ</li><li>Linux สำหรับบน Ubuntu หรือ Linux ในสาย Debian</li><li>Mac OS X เข้าไปที่ <a data-from-md="" href="https://www.python.org/download/" title="https://www.python.org/download/">https://www.python.org/download/</a></li></ul>
<p>เมื่อติดตั้งแล้ว ผู้อ่านสามารถเขียนโปรแกรมภาษา Python ได้เลย</p>
<h3 id="เครื่องมือที่ใช้ในการเขียนภาษา-python">เครื่องมือที่ใช้ในการเขียนภาษา Python</h3>
<p>มีหลายโปรแกรม ผู้อ่านสามารถใช้ IDLE (Python GUI)</p>
<p>ในการเขียนโปรแกรมได้หรือจะใช้โปรแกรมอย่าง Notepad++ หรือ text editor<br />ต่าง ๆ และ IDLE ในการเขียนได โดยบันทึกไฟล์เป็นนามสกุล .py<br />นอกจากนี้ เราขอแนะนำ PyCharm เป็น IDLE ที่น่าใช้งาน โหลดฟรีได้ที่ <a data-from-md="" href="http://www.jetbrains.com/pycharm/" title="http://www.jetbrains.com/pycharm/">http://www.jetbrains.com/pycharm/</a> เลือกรุ่นที่เป็น Community Edition</p>
<p><b>โปรแกรมแรก Hello world.py</b></p>
<p><b>โค้ด</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-built_in">print</span> (<span class="hljs-string">"Hello world"</span>)
<span class="hljs-comment"># ผลลัพธ์: Hello world</span></code></pre>
</div>
<h2 id="บทที่-2-ชนิดข้อมูลพื้นฐาน">บทที่ 2 ชนิดข้อมูลพื้นฐาน</h2>
<p>ข้อมูล คือ ข้อเท็จจริง นี้คงเป็นกฎที่หลาย ๆ ท่านคงเคยศึกษามา<br />บทนี้จะกล่าวถึงเรื่อง ชนิดของข้อมูลพื้นฐาน<br />ซึ่งเป็นสิ่งสำคัญที่ทุกท่านต้องรู้ก่อนเขียนโปรแกรมในภาษา Python</p>
<p>ใน Python มีชนิดข้อมูลหลายประเภท มีชนิดข้อมูลธรรมดาเพียง 3 ชนิด ได้แก่</p>
<ol><li>จำนวนเต็ม (Integer)</li><li>จำนวนจริง (Float)</li><li>สายอักขระ หรือ สตริง (String)</li></ol>
<p>ข้อมูลแบบซับซ้อนอีก 2 ชนิดดังนี้</p>
<ol><li>รายการ หรือ ลิสต์ (List)</li><li>พจนานุกรม หรือ ดิกชันนารี (Dictionary)</li></ol>
<p>ข้อมูลซับซ้อนนี้หมายถึง ข้อมูลนี้ประกอบไปด้วยข้อมูลอื่นที่อยู่ภายในแล้วแต่การใช้งาน ถ้าแบ่งเป็นประเภทใหญ่ ๆ จะได้ดังนี้</p>
<ol><li>ตรรกกะ</li><li>ตัวเลข</li><li>ลำดับ มีให้เลือกนำไปใช้งาน 3 ชนิด ดังนี้
<ol><li>สายอักขระ หรือ สตริง (String)</li><li>ทูเปิ้ล (Tuple)</li><li>รายการ หรือ ลิสต์ (List)</li></ol>
</li><li>จับคู่ (Mapping)</li></ol>
<h3 id="list-ใน-python">List ใน Python</h3>
<p>ในภาษา Python ไม่มีข้อมูลชนิดอาร์เรย์ (array) เหมือนกับภาษาอื่น<br />แต่สามารถใช้ข้อมูลชนิดลิสต์แทนอาร์เรย์ได้ โดยชื่อชนิดลิสต์ คือ list</p>
<p>ข้อมูลชนิดนี้จะเรียงต่อกันในลิสต์ของตัวแปรและคั่นข้อมูลด้วยเครื่องหมาย , ครอบด้วยเครื่องหมาย square brackets [" และ "]</p>
<p>มีลักษณะดังนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code>
[<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>]
</code></pre>
</div>
<p>สามารถดึงข้อมูลจากลิสต์มาใช้งานได้ดังนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code>a = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>]
<span class="hljs-built_in">print</span>(a[<span class="hljs-number">2</span>]) <span class="hljs-comment"># output: 3</span></code></pre>
</div>
<p>และ</p>
<div class="joplin-editable">
<pre class="hljs"><code>b = [[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>], [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]]
<span class="hljs-built_in">print</span>(b[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>]) <span class="hljs-comment"># output: 1</span></code></pre>
</div>
<p><b>การดำเนินการลิสต์</b></p>
<ul><li>len() เป็นคำสั่งนับจำนวนสมาชิกในลิสต์</li><li>list+list เป็นคำสั่งรวมสมาชิกของลิสต์ตัวอย่างเช่น<code class="inline-code" spellcheck="false">[1, 2] + [3, 4]</code>ผลลัพธ์<code class="inline-code" spellcheck="false">[1, 2, 3, 4]</code></li><li>เช็คสมาชิกในลิสต์ เช่น<code class="inline-code" spellcheck="false">3 in [1, 2, 3]</code>ผลลัพธ์<code class="inline-code" spellcheck="false">True</code></li><li>เพิ่มข้อมูลเข้าไปยังข้อมูลชนิด List</li></ul>
<p>ใช้คำสั่ง</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-built_in">list</span>.append(วัตถุ)</code></pre>
</div>
<ul><li>Iteration เป็นการแยกข้อมูลออกมาจากลิสต์ เช่น<code class="inline-code" spellcheck="false">for x in [1, 2, 3]: print (x),</code>ผลลัพธ์<code class="inline-code" spellcheck="false">1 2 3</code></li><li>คำสั่ง insert(x,y)<br />เป็นคำสั่งสำหรับเพิ่มข้อมูลเข้าไปแซงข้อมูลในตำแหน่งนั้น โดย x เป็น<br />ตำแหน่ง index และ y เป็นข้อมูลที่ต้องการแทนที่</li></ul>
<p><b>ตัวอย่าง</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>a= [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>]a.insert(<span class="hljs-number">1</span>,<span class="hljs-string">"hi"</span>)
<span class="hljs-built_in">print</span>(a)</code></pre>
</div>
<p>ผลลัพธ์</p>
<div class="joplin-editable">
<pre class="hljs"><code>[<span class="hljs-number">1</span>, <span class="hljs-string">'hi'</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]</code></pre>
</div>
<h3 id="อาร์เรย์-array-เบื้องต้นใน-python">อาร์เรย์ (array) เบื้องต้นใน Python</h3>
<p>อาร์เรย์ (array) เป็นข้อมูลชนิดหนึ่ง เป็นโครงสร้างข้อมูล แต่ว่า Python ไม่สนับสนุนอาร์เรย์ชนิดนี้โดยตรง จึงต้องใช้ชนิดข้อมูลที่เรียกว่ารายการ ซึ่งเกือบเหมือนกับอาร์เรย์ แต่สามารถเข้าถึงได้เพียงหนึ่งดัชนี</p>
<p><b>อาร์เรย์ 1 มิติ</b></p>
<p>ใน Python จะมีรูปแบบดังนี้ [1,2,3,4,5,6]</p>
<div class="joplin-editable">
<pre class="hljs"><code>a = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>]
<span class="hljs-built_in">print</span>(a[<span class="hljs-number">2</span>])</code></pre>
</div>
<p>จะได้ผลลัพธ์ คือ 3 จะเห็นได้ว่าใน python จะนับอาร์เรย์ตัวที่ 1 เป็น 0 ไล่ไปเรื่อย ๆ</p>
<p>หากต้องการจำนวน 3 ถึง 5 ใช้คำสั่ง</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-built_in">print</span>(a[<span class="hljs-number">2</span>:<span class="hljs-number">5</span>])</code></pre>
</div>
<p>ผลลัพธ์จะได้ [3, 4, 5]</p>
<p>ถ้าต้องการค่าข้อมูลบนอาร์เรย์ ตามตำแหน่งคอลัมน์</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-built_in">print</span>(a[<span class="hljs-number">5</span>:])</code></pre>
</div>
<p>จะได้ผลลัพธ์ [6]</p>
<p>ต่อมาเราจะเปลี่ยนค่าข้อมูลในอาร์เรย์กัน</p>
<p>เช่น a[5] จากเดิมเป็น [6] หากใช้คำสั่ง</p>
<div class="joplin-editable">
<pre class="hljs"><code>>>a[<span class="hljs-number">5</span>] = <span class="hljs-number">11</span>
>><span class="hljs-built_in">print</span>(a[<span class="hljs-number">5</span>:])
[<span class="hljs-number">11</span>]</code></pre>
</div>
<p>จะเห็นได้ว่าข้อมูลใหม่จะทับข้อมูลเก่า ข้อมูลเก่าจะหายไปเป็นไปตามหลักการเก็บข้อมูลของคอมพิวเตอร์</p>
<p>หากใช้คำสั่ง print(a[:]) คือแสดงอาร์เรย์ทั้งหมดออกมา</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(a[:])
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">11</span>]</code></pre>
</div>
<p><b>อาร์เรย์ 2 มิติ</b></p>
<p>อาร์เรย์ 2 มิติมีการจัดเรียงข้อมูลในแถว / คอลัมน์ สามารถเปรียบเทียบได้กับเมทริกซ์ในคณิตศาสตร์</p>
<p>ใน Python อาร์เรย์ 2 มิติ จะมีรูปแบบเป็น [[1, 2], [3, 4]]</p>
<div class="joplin-editable">
<pre class="hljs"><code>b = [[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>], [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]]</code></pre>
</div>
<p>ถ้าเป็นรูปแบบเมทริกซ์ในคณิตศาสตร์จะเป็น</p>
<p>b = [1, 2]</p>
<p>[3, 4]</p>
<p>หากต้องการดึงข้อมูลมาใช้จากอาร์เรย์ 2 มิติ ใช้คำสั่งดังนี้ เช่น</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>b = [[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>], [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]]
<span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(b[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>])
<span class="hljs-number">1</span></code></pre>
</div>
<p>แถวที่ 1 หลักที่ 1 คือ 1</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(b[<span class="hljs-number">0</span>][<span class="hljs-number">1</span>])
<span class="hljs-number">2</span></code></pre>
</div>
<p>แถวที่ 1 หลักที่ 2 คือ 2</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(b[<span class="hljs-number">1</span>][<span class="hljs-number">0</span>])
<span class="hljs-number">3</span></code></pre>
</div>
<p>แถวที่ 2 หลักที่ 1 คือ 3</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(b[<span class="hljs-number">1</span>][<span class="hljs-number">1</span>])
<span class="hljs-number">4</span></code></pre>
</div>
<p>แถวที่ 2 หลักที่ 2 คือ 4</p>
<p>หากต้องการแสดงทั้งแถวและคอลัมน์ใช้คำสั่ง</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(b[<span class="hljs-number">0</span>:][<span class="hljs-number">0</span>:])
[[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>], [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]]</code></pre>
</div>
<p>หากต้องการเฉพาะแถวที่ 1 ใช้คำสั่ง</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(b[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>:])
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>]</code></pre>
</div>
<p><b>อาร์เรย์ 3 มิติ</b></p>
<p>มีลักษณะการใช้งานเหมือนกับที่ผ่านมา แต่มีอาร์เรย์เพิ่มอีกมิติ ตัวอย่างเช่น</p>
<p>[[[1, 2, 3], [4, 5, 6], [7, 8, 9]],</p>
<p>[[10, 11, 12], [13, 14, 15], [16, 17, 18]],</p>
<p>[[19, 20, 21], [22, 23, 24], [25, 26, 27]]]</p>
<p>การนำไปใช้งาน</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>d = [[[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], [<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>], [<span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>]],
[[<span class="hljs-number">10</span>, <span class="hljs-number">11</span>, <span class="hljs-number">12</span>], [<span class="hljs-number">13</span>, <span class="hljs-number">14</span>, <span class="hljs-number">15</span>], [<span class="hljs-number">16</span>, <span class="hljs-number">17</span>, <span class="hljs-number">18</span>]],
[[<span class="hljs-number">19</span>, <span class="hljs-number">20</span>, <span class="hljs-number">21</span>], [<span class="hljs-number">22</span>, <span class="hljs-number">23</span>, <span class="hljs-number">24</span>], [<span class="hljs-number">25</span>, <span class="hljs-number">26</span>, <span class="hljs-number">27</span>]]]
<span class="hljs-meta">>>> </span>d[<span class="hljs-number">0</span>][<span class="hljs-number">1</span>]
[<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>]
<span class="hljs-meta">>>> </span>d[<span class="hljs-number">0</span>][<span class="hljs-number">1</span>][<span class="hljs-number">2</span>]
<span class="hljs-number">6</span></code></pre>
</div>
<p>หากต้องการคำนวณมากกว่านั้น แนะนำให้ใช้โมดูล <a data-from-md="" href="http://www.numpy.org/" title="http://www.numpy.org/">numpy</a> แทนดีกว่า</p>
<h3 id="การดําเนินการแบบตรรกะ-boolean-operations-ใน-python-3">การดำเนินการแบบตรรกะ (Boolean Operations) ใน Python 3</h3>
<p>การดำเนินการแบบตรรกะ (Boolean Operations) ใน Python 3 โดยใช้ตรรกะศาสตร์เข้ามา โดยการใช้หลักเหตุและผล ผลลัพธ์ที่ได้จะได้ จริง<br />(True) และ เท็จ (False)</p>
<p>หากผู้อ่านเคยเรียนวิชาตรรกะศาสตร์มาจะเข้าใจบทความนี้ยิ่งขึ้น</p>
<p><b>การเปรียบเทียบประพจน์</b></p>
<p>จริง และ จริง ได้ จริง ที่เหลือเท็จ</p>
<p>เท็จ หรือ เท็จ ได้ เท็จ ที่เหลือจริง</p>
<p>ถ้า จริง แล้ว เท็จ ได้ เท็จ ที่หลือจริง</p>
<p>จริง ก็ต่อเมื่อ จริง , เท็จ ก็ต่อเมื่อ เท็จ ได้ จริง ที่เหลือเท็จ</p>
<p><b>การดำเนินการแบบตรรกะใน Python 3</b></p>
<table>
<thead>
<tr>
<th>การดำเนินการ</th>
<th>ความหมาย</th>
<th>ผลลัพธ์</th>
</tr>
</thead>
<tbody>
<tr>
<td>x or y</td>
<td>x หรือ y</td>
<td>ถ้า x = True , y = True ดังนั้น x หรือ y ได้จริง (True)</td>
</tr>
<tr>
<td>x and y</td>
<td>x และ y</td>
<td>ถ้า x = False , y = True ดังนั้น x และ y ได้เท็จ (False)</td>
</tr>
<tr>
<td>not x == y</td>
<td>ถ้า x แล้ว y</td>
<td>ถ้า x = True , y = False ดังนั้น ถ้า x แล้ว y ได้จริง (True)</td>
</tr>
</tbody>
</table>
<h3 id="ทูเพิล-tuple-ใน-python">ทูเพิล (Tuple) ใน Python</h3>
<p>ทูเพิล (Tuple) คือ โครงสร้างข้อมูลแบบเรียงลำดับ (List) ที่ไม่สามารถแก้ไขข้อมูลที่อยู่ใน<br />tuple ได้ ตัวอย่างทูเพิล(Tuple)</p>
<div class="joplin-editable">
<pre class="hljs"><code>Tuple1 = (<span class="hljs-number">5</span>,<span class="hljs-number">4</span>,<span class="hljs-number">3</span>)
<span class="hljs-built_in">print</span> (Tuple1)</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<p><code class="inline-code" spellcheck="false">(5,4,3)</code></p>
<p><b>เมื่อเปรียบเทียบความแตกต่างระหว่างทูเพิล(Tuple) กับแบบเรียงลำดับ (List)ตัวอย่าง</b> เช่น</p>
<p>กรณี List</p>
<div class="joplin-editable">
<pre class="hljs"><code>List1 = [<span class="hljs-number">5</span>,<span class="hljs-number">4</span>,<span class="hljs-number">3</span>]
List1.append(<span class="hljs-number">2</span>)
<span class="hljs-built_in">print</span> (List1)</code></pre>
</div>
<p><b>ผลลัพธ์</b><br /><code class="inline-code" spellcheck="false">>>[5, 4, 3, 2]</code><br />กรณี <b>Tuple</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>Tuple1 = (<span class="hljs-number">5</span>,<span class="hljs-number">4</span>,<span class="hljs-number">3</span>)
<span class="hljs-built_in">print</span> (Tuple1)</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<p><code class="inline-code" spellcheck="false">>>(5,4,3)</code><br />หากต้องการเพิ่มข้อมูลเข้าไปใน Tuple</p>
<div class="joplin-editable">
<pre class="hljs"><code>Tuple2 = (<span class="hljs-number">5</span>,<span class="hljs-number">4</span>,<span class="hljs-number">3</span>)
Tuple2.append(<span class="hljs-number">2</span>)
<span class="hljs-built_in">print</span> (Tuple2)</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>Tuple2 = (<span class="hljs-number">5</span>,<span class="hljs-number">4</span>,<span class="hljs-number">3</span>)
<span class="hljs-meta">>>> </span>Tuple2.append(<span class="hljs-number">2</span>)
Traceback (most recent call last):
File <span class="hljs-string">"<pyshell#11>"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> <module>
Tuple2.append(<span class="hljs-number">2</span>)
AttributeError: <span class="hljs-string">'tuple'</span> <span class="hljs-built_in">object</span> has no attribute <span class="hljs-string">'append'</span></code></pre>
</div>
<p>จะพบว่าเราไม่สามารถใช้ append เพิ่ม 2 เข้าไปใน Tuple ได้<br />นี่คือข้อแตกต่างระหว่างข้อมูลแบบเรียงลำดับ (List) กับทูเพิล (Tuple)</p>
<h3 id="ตัวแปรข้อมูล-dictionary-ใน-python">ตัวแปรข้อมูล Dictionary ใน Python</h3>
<p>Dictionary เป็นอาเรย์ที่สามารถใช้สตริงเป็นคีย์ (key) ในการเข้าถึงข้อมูลได้ โดยปกติอาเรย์จะมีคีย์เป็นจำนวนเต็มนับตั้งแต่ 0 ถึง n-1</p>
<p>โดยชนิดข้อมูลประเภทจับคู่ ใน Python จะครอบเริ่มด้วย { และลงท้ายด้วย } ตามนี้</p>
<blockquote>
<p>{'ก':1,'ข':2,'ค':3}</p>
</blockquote>
<p>หมายความว่าในดิกชั่นนารีนี้ มีค่า 3 ค่า คือ 1,2 และ 3 และมีคีย์ 3 คีย์คือ 'ก','ข' และ 'ค'</p>
<p>ในการเรียกใช้งานข้อมูลในดิกชั่นนารี สามารถทำได้โดยการอ้างอิงคีย์ใน [คีย์] เช่น</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>{<span class="hljs-string">'ก'</span>:<span class="hljs-number">1</span>,<span class="hljs-string">'ข'</span>:<span class="hljs-number">2</span>,<span class="hljs-string">'ค'</span>:<span class="hljs-number">3</span>}[<span class="hljs-string">'ข'</span>]
<span class="hljs-number">2</span></code></pre>
</div>
<p>สรุปตัวแปร Dictionary ใน Python คืออะไร?</p>
<blockquote>
<p>Dictionary คือตัวแปรข้อมูลประเภท key, value</p>
</blockquote>
<p>มีรูปแบบดังนี้</p>
<blockquote>
<p>{key:value}</p>
</blockquote>
<p>ตัวอย่างเช่น</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>money = {<span class="hljs-string">'Art'</span>:<span class="hljs-string">'250'</span>, <span class="hljs-string">'Mark'</span>:<span class="hljs-string">'549'</span>}
<span class="hljs-meta">>>> </span>money
{<span class="hljs-string">'Mark'</span>: <span class="hljs-string">'549'</span>, <span class="hljs-string">'Art'</span>: <span class="hljs-string">'250'</span>}
<span class="hljs-meta">>>> </span>money[<span class="hljs-string">'Mark'</span>]
<span class="hljs-string">'549'</span>
<span class="hljs-meta">>>> </span>money[<span class="hljs-string">'Art'</span>]
<span class="hljs-string">'250'</span></code></pre>
</div>
<p>โดยสร้างตัวแปร money เก็บจำนวนเงินของ Art และ Mark โดยใน {'Art':'250', 'Mark':'549'} ข้างหน้า : คือ Key ข้างหลัง : คือ value<br />บรรทัดที่ 4 ต่อมา เราได้สั่ง money['Mark'] คือ ให้แสดงค่าของคีย์ Mark ที่เก็บอยู่ในตัวแปร money</p>
<p>นอกจากนั้นเรายังสามารถสร้างตัวแปรข้อมูล Dictionary ด้วยคำสั่ง dict() ได้ดังนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>name = <span class="hljs-built_in">dict</span>(name=<span class="hljs-string">'Mark'</span>, age=<span class="hljs-number">18</span>)
<span class="hljs-meta">>>> </span>name
{<span class="hljs-string">'name'</span>: <span class="hljs-string">'Mark'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">18</span>}</code></pre>
</div>
<p>และนอกจากกำหนดค่าแล้วเราสามารถเพิ่มค่าเข้าไปยัง Dictionary ได้ดังนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>buy = {} <span class="hljs-comment">#ข้างในนี้ Dictionary ว่างเปล่า</span>
<span class="hljs-meta">>>> </span>buy[<span class="hljs-string">'Mark'</span>] = <span class="hljs-string">'70'</span> <span class="hljs-comment">#เพิ่มคีย์ Mark และค่า 70 เข้าไปยัง buy</span>
<span class="hljs-meta">>>> </span>buy[<span class="hljs-string">'Art'</span>] = <span class="hljs-string">'36'</span> <span class="hljs-comment">#เพิ่มคีย์ Art และค่า 36 เข้าไปยัง buy</span>
<span class="hljs-meta">>>> </span>buy
{<span class="hljs-string">'Mark'</span>: <span class="hljs-string">'70'</span>, <span class="hljs-string">'Art'</span>: <span class="hljs-string">'36'</span>}</code></pre>
</div>
<p>ต่อไปเราจะมาลองทำ Dictionary ซ้อนในค่าของคีย์ใน Dictionary</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>money = {<span class="hljs-string">'Art'</span>:<span class="hljs-string">'250'</span>, <span class="hljs-string">'Mark'</span>:<span class="hljs-string">'549'</span>}
<span class="hljs-meta">>>> </span>money[<span class="hljs-string">'Pop'</span>] = {<span class="hljs-string">'buy'</span>:<span class="hljs-number">123</span>} <span class="hljs-comment">#สร้างคีย์ Pop ขึ้นมาแล้วเก็บค่า {'buy':123} เข้าไป</span>
<span class="hljs-meta">>>> </span>money
{<span class="hljs-string">'Pop'</span>: {<span class="hljs-string">'buy'</span>: <span class="hljs-number">123</span>}, <span class="hljs-string">'Mark'</span>: <span class="hljs-string">'549'</span>, <span class="hljs-string">'Art'</span>: <span class="hljs-string">'250'</span>}
<span class="hljs-meta">>>> </span>money[<span class="hljs-string">'Pop'</span>] <span class="hljs-comment">#แสดงค่าข้อมูลในคีย์ Pop</span>
{<span class="hljs-string">'buy'</span>: <span class="hljs-number">123</span>}
<span class="hljs-meta">>>> </span>money[<span class="hljs-string">'Pop'</span>][<span class="hljs-string">'buy'</span>] <span class="hljs-comment">#แสดงค่าข้อมูลคีย์ buy ในคีย์ Pop</span>
<span class="hljs-number">123</span></code></pre>
</div>
<p><b>คำสั่งกับตัวแปรข้อมูล Dictionary ใน Python</b></p>
<p><b>คำสั่ง dict.keys(), dict.values(), dict.items()</b></p>
<ul><li>คำสั่ง <b>dict.keys()</b> เป็นคำสั่งสำหรับดึงคีย์ทั้งหมดใน Dictionary ออกมา</li><li>คำสั่ง <b>dict.values()</b> เป็นคำสั่งสำหรับดึงค่าในคีย์ทั้งหมดใน Dictionary ออกมา</li><li>คำสั่ง <b>dict.items()</b> เป็นคำสั่งสำหรับดึงทั้งค่าและคีย์ทั้งหมดใน Dictionary ออกมา</li></ul>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>money = {<span class="hljs-string">'Art'</span>:<span class="hljs-string">'250'</span>, <span class="hljs-string">'Mark'</span>:<span class="hljs-string">'549'</span>}
<span class="hljs-meta">>>> </span><span class="hljs-built_in">list</span>(money.keys())
[<span class="hljs-string">'Mark'</span>, <span class="hljs-string">'Art'</span>]
<span class="hljs-meta">>>> </span><span class="hljs-built_in">list</span>(money.values())
[<span class="hljs-string">'549'</span>, <span class="hljs-string">'250'</span>]
<span class="hljs-meta">>>> </span><span class="hljs-built_in">list</span>(money.items())
[(<span class="hljs-string">'Mark'</span>, <span class="hljs-string">'549'</span>), (<span class="hljs-string">'Art'</span>, <span class="hljs-string">'250'</span>)]
</code></pre>
</div>
<p><b>คำสั่ง dict.get()</b></p>
<p>เป็นคำสั่งสำหรับรับค่าในคีย์ของ Dictionary ที่ต้องการ ตัวอย่างเช่น</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>money = {<span class="hljs-string">'Art'</span>:<span class="hljs-string">'250'</span>, <span class="hljs-string">'Mark'</span>:<span class="hljs-string">'549'</span>}
<span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(money.get(<span class="hljs-string">'Art'</span>))
<span class="hljs-number">250</span>
<span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(money.get(<span class="hljs-string">'Mark'</span>))
<span class="hljs-number">549</span>
</code></pre>
</div>
<p><b>คำสั่ง dict.update()</b></p>
<p>เป็นคำสั่งสำหรับใช้เปลี่ยนแปลงค่าข้อมูลในคีย์ของ Dictionary ที่ต้องการ ตัวอย่างเช่น</p>
<div class="joplin-editable">
<pre class="hljs"><code>
<span class="hljs-meta">>>> </span>money = {<span class="hljs-string">'Art'</span>:<span class="hljs-string">'250'</span>, <span class="hljs-string">'Mark'</span>:<span class="hljs-string">'549'</span>}
<span class="hljs-meta">>>> </span>money2 = {<span class="hljs-string">'Ploy'</span>:<span class="hljs-number">300</span>} <span class="hljs-comment">#สร้าง Dictionary</span>
<span class="hljs-meta">>>> </span>money.update(money2) <span class="hljs-comment">#เพิ่ม Dictionary ของ money2 เข้าไปยัง Dictionary ของ money</span>
<span class="hljs-meta">>>> </span>money
{<span class="hljs-string">'Mark'</span>: <span class="hljs-string">'549'</span>, <span class="hljs-string">'Art'</span>: <span class="hljs-string">'250'</span>, <span class="hljs-string">'Ploy'</span>: <span class="hljs-number">300</span>}
<span class="hljs-meta">>>> </span>money.update({<span class="hljs-string">'Art'</span>:<span class="hljs-number">115</span>}) <span class="hljs-comment">#ปรับเปลี่ยนค่าข้อมูลของคีย์ Art ใน Dictionary ของ money</span>
<span class="hljs-meta">>>> </span>money
{<span class="hljs-string">'Mark'</span>: <span class="hljs-string">'549'</span>, <span class="hljs-string">'Art'</span>: <span class="hljs-number">115</span>, <span class="hljs-string">'Ploy'</span>: <span class="hljs-number">300</span>}
</code></pre>
</div>
<p><b>คำสั่ง dict.pop()</b></p>
<p>เป็นคำสั่งสำหรับดึงค่าข้อมูลในคีย์ที่ต้องการออกแล้ว ให้ลบคีย์นั้นทิ้งใน Dictionary นั้น ตัวอย่างเช่น</p>
<div class="joplin-editable">
<pre class="hljs"><code>
<span class="hljs-meta">>>> </span>money = {<span class="hljs-string">'Mark'</span>: <span class="hljs-string">'549'</span>, <span class="hljs-string">'Art'</span>: <span class="hljs-string">'115'</span>, <span class="hljs-string">'Ploy'</span>: <span class="hljs-number">300</span>}
<span class="hljs-meta">>>> </span>money.pop(<span class="hljs-string">'Art'</span>)
<span class="hljs-number">115</span>
<span class="hljs-meta">>>> </span>money
{<span class="hljs-string">'Mark'</span>: <span class="hljs-string">'549'</span>, <span class="hljs-string">'Ploy'</span>: <span class="hljs-number">300</span>}
</code></pre>
</div>
<p><b>คำสั่ง dict.fromkeys()</b></p>
<p>ถ้าต้องการให้ค่าสำหรับแต่ละคีย์เหมือนกัน เราสามารถใช้ fromkeys() เพื่อ Dictionary ด้วยคีย์เดียวกันได้ ตัวอย่างเช่น</p>
<div class="joplin-editable">
<pre class="hljs"><code>
<span class="hljs-meta">>>> </span>a = {}
<span class="hljs-meta">>>> </span>a.fromkeys([<span class="hljs-string">'1'</span>,<span class="hljs-string">'2'</span>,<span class="hljs-string">'3'</span>,<span class="hljs-string">'4'</span>],<span class="hljs-string">'Cat'</span>)
{<span class="hljs-string">'1'</span>: <span class="hljs-string">'Cat'</span>, <span class="hljs-string">'4'</span>: <span class="hljs-string">'Cat'</span>, <span class="hljs-string">'2'</span>: <span class="hljs-string">'Cat'</span>, <span class="hljs-string">'3'</span>: <span class="hljs-string">'Cat'</span>}
</code></pre>
</div>
<p><b>คำสั่ง dict.clear()</b></p>
<p>เป็นคำสั่งสำหรับล้างข้อมูลทั้งหมดใน Dictionary ตัวอย่างเช่น</p>
<div class="joplin-editable">
<pre class="hljs"><code>
<span class="hljs-meta">>>> </span>money = {<span class="hljs-string">'Mark'</span>: <span class="hljs-string">'549'</span>, <span class="hljs-string">'Art'</span>: <span class="hljs-string">'115'</span>, <span class="hljs-string">'Ploy'</span>: <span class="hljs-number">300</span>}
<span class="hljs-meta">>>> </span>money.clear()
<span class="hljs-meta">>>> </span>money
{}
</code></pre>
</div>
<h3 id="byte-array-ในภาษาไพทอน-python-3">Byte Array ในภาษาไพทอน Python 3</h3>
<p>ในภาษาไพทอนจะมีข้อมูลชนิดหนึ่ง คือ ข้อมูลไบต์ (Byte) เป็น bytes-like<br />object (วัตถุที่เหมือนกับไบต์)<br />โดยในภาษาไพทอนจะมีสัญลักษณ์บ่งบอกขนิดข้อมูลนี้ b''</p>
<p><b>ตัวอย่างเช่น</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>a = <span class="hljs-string">b'Hello'</span>
<span class="hljs-built_in">print</span>(a)
<span class="hljs-built_in">print</span>(<span class="hljs-built_in">type</span>(a)</code></pre>
</div>
<p>ผลลัพธ์</p>
<div class="joplin-editable">
<pre class="hljs"><code>b<span class="hljs-string">'Hello'</span>
<<span class="hljs-keyword">class</span> <span class="hljs-string">'bytes'</span>></code></pre>
</div>
<p>มาเริ่มคำสั่ง Byte Array ในภาษาไพทอน 3 กัน</p>
<p><b>คำสั่ง</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-built_in">bytearray</span>([source[, encoding[, errors]]])</code></pre>
</div>
<p>เป็นคลาสลำดับเปลี่ยนแปลงได้ของจำนวนเต็มในช่วง 0 < = x < 256</p>
<p>สามารถสร้าง bytearray ได้จากข้อมูลชนิด list หรือไบต์ได้ดังนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-comment"># ข้อมูลไบต์</span>
<span class="hljs-meta">>>> </span>b = <span class="hljs-built_in">bytearray</span>(<span class="hljs-string">b"Hello World"</span>)
<span class="hljs-meta">>>> </span>b.split()
[<span class="hljs-built_in">bytearray</span>(<span class="hljs-string">b'Hello'</span>), <span class="hljs-built_in">bytearray</span>(<span class="hljs-string">b'World'</span>)]
<span class="hljs-meta">>>> </span>b[:<span class="hljs-number">5</span>]
<span class="hljs-string">b"It"</span>
<span class="hljs-meta">>>> </span>b
<span class="hljs-built_in">bytearray</span>(<span class="hljs-string">b'It World'</span>)
<span class="hljs-meta">>>> </span><span class="hljs-comment"># ข้อมูล list</span>
<span class="hljs-meta">>>> </span>key1 = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]
<span class="hljs-meta">>>> </span>key2 = <span class="hljs-built_in">bytearray</span>(key1)
<span class="hljs-meta">>>> </span>key2
<span class="hljs-built_in">bytearray</span>(<span class="hljs-string">b'\x01\x02\x03'</span>)</code></pre>
</div>
<p>รับค่าขนาดไบต์ได้โดยอ้าอิงข้อมูลในข้อมูลชนิดไบต์ :</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>b = <span class="hljs-built_in">bytearray</span>(<span class="hljs-string">b"Hello World"</span>)
<span class="hljs-meta">>>> </span>b[:<span class="hljs-number">1</span>]
<span class="hljs-built_in">bytearray</span>(<span class="hljs-string">b'H'</span>)
<span class="hljs-meta">>>> </span>b[<span class="hljs-number">1</span>]
<span class="hljs-number">101</span>
<span class="hljs-meta">>>> </span>b[:<span class="hljs-number">0</span>]
<span class="hljs-built_in">bytearray</span>(<span class="hljs-string">b''</span>)
<span class="hljs-meta">>>> </span>b[<span class="hljs-number">0</span>]
<span class="hljs-number">72</span>
<span class="hljs-meta">>>> </span><span class="hljs-comment">#ลูปจำนวนไบต์ทั้งหมดออกมา</span>
<span class="hljs-meta">>>> </span><span class="hljs-keyword">for</span> c <span class="hljs-keyword">in</span> b: <span class="hljs-built_in">print</span>(c)
...
<span class="hljs-number">72</span>
<span class="hljs-number">101</span>
<span class="hljs-number">108</span>
<span class="hljs-number">108</span>
<span class="hljs-number">111</span>
<span class="hljs-number">32</span>
<span class="hljs-number">87</span>
<span class="hljs-number">111</span>
<span class="hljs-number">114</span>
<span class="hljs-number">108</span>
<span class="hljs-number">100</span>
>>>
<span class="hljs-meta">>>> </span><span class="hljs-keyword">for</span> c <span class="hljs-keyword">in</span> key2: <span class="hljs-built_in">print</span>(c)
...
<span class="hljs-number">1</span>
<span class="hljs-number">2</span>
<span class="hljs-number">3</span></code></pre>
</div>
<p>อ่านเอกสารเพิ่มเติมได้ที่ <a data-from-md="" href="https://docs.python.org/3/library/functions.html#bytearray" title="https://docs.python.org/3/library/functions.html#bytearray">https://docs.python.org/3/library/functions.html#bytearray</a></p>
<h2 id="บทที่-3-การแสดงผลข้อมูลใน-python-3">บทที่ 3 การแสดงผลข้อมูลใน Python 3</h2>
<p>การแสดงผลข้อมูลถือเป็นสิ่งสำคัญเพื่อให้รู้ผลลัพธ์จากการประมวลผลของคอมพิวเตอร์<br />ถ้าไม่มีการแสดงผลการทำงานของโปรแกรม<br />การที่เขียนโปรแกรมนั้นจะไม่มีประโยชน์อะไรเลย<br />เพราะไม่สามารถนำข้อมูลไปใช้งานได้</p>
<h3 id="รูปแบบการแสดงผลข้อมูลใน-python-3">รูปแบบการแสดงผลข้อมูลใน Python 3</h3>
<blockquote>
<p>print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)</p>
</blockquote>
<ul><li>objects คือ วัตถุ</li><li>sep คือ การแยก</li><li>end คือ การขึ้นบรรทัดใหม่</li></ul>
<h3 id="ตัวแทนชนิดของข้อมูล">ตัวแทนชนิดของข้อมูล</h3>
<p>%s - สตริง เช่น ข้อความ</p>
<p>%d - จำนวนเต็ม</p>
<p>%f - เลขทศนิยม</p>
<p>%.f - เลขทศนิยมมีจำนวนคงตัวเลขทางด้านขวาของจุดทศนิยม</p>
<p>%x/%X - จำนวนเต็มใน hex แทน (พิมพ์เล็ก/ใหญ่)</p>
<h3 id="ตัวอย่างการแสดงผลข้อมูลใน-python-3"><b>ตัวอย่างการแสดงผลข้อมูลใน Python 3</b></h3>
<p><b>ตัวอย่างที่ 1</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-built_in">print</span>(<span class="hljs-string">"Hello World"</span>)</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<p>Hello World</p>
</blockquote>
<p>อธิบาย</p>
<p>ตัวอย่างนี้แสดงข้อความที่กำหนดออกมาทางจอภาพเท่านั้น ไม่มีการแสดงข้อมูลอื่นเพิ่มเติม</p>
<p><b>ตัวอย่างที่ 2</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-built_in">print</span> (<span class="hljs-string">"1+1 = %d"</span> % (<span class="hljs-number">2</span>))</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<p>1+1 = 2</p>
</blockquote>
<p>อธิบาย</p>
<p>ในตัวอย่างนี้มีการใช้ String Formatting<br />ในแบบข้อความผสมกับตัวแทนชนิดข้อมูล มีการรับค่าคงที่เข้า คือ 2<br />เข้ามาแทนที่ตัวแทนชนิดข้อมูลในประโยค</p>
<p><b>ตัวอย่างที่ 3</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>num = <span class="hljs-number">100</span>
<span class="hljs-built_in">print</span> (<span class="hljs-string">"%d/2"</span> % (num))</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<p>100/2</p>
</blockquote>
<p>อธิบาย</p>
<p>ในตัวอย่างนี้มีการใช้ String Formatting ในแบบข้อความผสมกับตัวแทนชนิดข้อมูล โดยมีการเรียกใช้ตัวแปรเข้ามาแทนที่ตัวแทนชนิดข้อมูล</p>
<p><b>ตัวอย่างที่ 4</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-built_in">print</span> (<span class="hljs-string">"Are you ok?"</span>,<span class="hljs-string">"\n"</span>)</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<p>Are you ok?</p>
</blockquote>
<p>อธิบาย</p>
<p>ในตัวอย่างนี้แสดงข้อความที่กำหนดออกมาทางจอภาพเท่านั้น และขึ้นบรรทัดใหม่โดยใช้ \n</p>
<h3 id="หากเราต้องการแสดงข้อมูลซ้ํา">หากเราต้องการแสดงข้อมูลซ้ำ</h3>
<p>print (ข้อความหรือตัวแปร*จำนวนที่ต้องการแสดงซ้ำ)</p>
<p><b>ตัวอย่างเช่น</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-built_in">print</span> (<span class="hljs-string">"Hello, World!"</span>*<span class="hljs-number">5</span>)</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<blockquote>
<blockquote>
<p>print ("Hello, World!"*5)</p>
</blockquote>
</blockquote>
</blockquote>
<p>Hello, World!Hello, World!Hello, World!Hello, World!Hello, World!</p>
<h2 id="บทที่-4-decimal-python">บทที่ 4 Decimal Python</h2>
<p>เรามาเรียนรู้การใช้ Decimal หรือเลขทศนิยมใน Python กัน</p>
<p>สิ่งหนึ่งที่โปรแกรมเมอร์รู้กันนั้นก็คือคอมพิวเตอร์ใช้เลขฐานสองเป็นภาษาเครื่อง<br />คือ 0 และ 1 ไม่ได้ใช้เลขฐานสิบดังที่มนุษย์ ทำให้การใช้ Decimal<br />หรือเลขทศนิยมในเลขฐานสอง จะไม่ตรงกับเลขทศนิยมในเลขฐานสิบได้<br />หากเราเขียนโปรแกรมเปรีบเทียบเช่น</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span> (<span class="hljs-number">0.05</span> + <span class="hljs-number">0.05</span> == <span class="hljs-number">0.1</span>)
<span class="hljs-literal">True</span></code></pre>
</div>
<p>จะเห็นได้ว่าได้ผลลัพธ์ที่ต้องการในระดับหนึ่ง แต่ถ้าเราเขียนโปรแกรมที่มีการทำงานวนซ้ำกันจำนวนหลาย ๆ ครั้งมาก ๆ กับเลขทศนิยม เช่น</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>aa = <span class="hljs-number">0.0</span>
<span class="hljs-meta">>>> </span><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">1000</span>):
aa += <span class="hljs-number">0.0001</span>
<span class="hljs-built_in">print</span>(<span class="hljs-built_in">repr</span>(aa))
<span class="hljs-number">0.0001</span>
<span class="hljs-number">0.0002</span>
<span class="hljs-number">0.00030000000000000003</span>
...
<span class="hljs-number">0.09980000000000183</span>
<span class="hljs-number">0.09990000000000183</span>
<span class="hljs-number">0.10000000000000184</span>
<span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span> (aa == <span class="hljs-number">1.0</span>)
<span class="hljs-literal">False</span></code></pre>
</div>
<p>จะเห็นได้ว่าโปรแกรมทำงานไม่ได้ผลลัพธ์ตามที่เราต้องการและออกแบบไว้<br />หากเราต้องการให้ทำงานเพื่อให้ได้ผลลัพธ์ที่ต้องการ เราต้องทำตามเอกสาร</p>
<p><a data-from-md="" href="https://www.python.org/dev/peps/pep-0327/" title="https://www.python.org/dev/peps/pep-0327/">PEP-327</a></p>
<p>เป็นสเปคของเลขทศนิยมฐานสิบใน Python ทำให้ได้ผลลัพธ์ที่ถูกต้องกว่า อย่าลืม from decimal import Decimal กัน เช่น</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> decimal <span class="hljs-keyword">import</span> Decimal
<span class="hljs-meta">>>> </span>b = Decimal(<span class="hljs-string">"0.0"</span>)
<span class="hljs-meta">>>> </span><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">1000</span>):
b += Decimal(<span class="hljs-string">"0.001"</span>)
<span class="hljs-built_in">print</span>(<span class="hljs-built_in">repr</span>(b))
Decimal(<span class="hljs-string">'0.001'</span>)
...
Decimal(<span class="hljs-string">'1.000'</span>)
<span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(b == Decimal(<span class="hljs-string">"1.0"</span>))
<span class="hljs-literal">True</span></code></pre>
</div>
<p>อ่านรายละเอียดเพิ่มเติมได้ที่</p>
<p><a data-from-md="" href="https://docs.python.org/3/library/decimal.html" title="https://docs.python.org/3/library/decimal.html">https://docs.python.org/3/library/decimal.html</a></p>
<h2 id="บทที่-5-การใช้งาน-range-ใน-python">บทที่ 5 การใช้งาน range ใน Python</h2>
<p>range เป็นคำสั่งสำหรับมีไว้ในการลำดับจำนวนตัวเลข เช่น แสดงตัวเลข 0 - 3<br />หรือแบบก้าวกระโดด 3,6,9 มีทั้งไปทาง + และ - ตามระบบเส้นจำนวนจริง</p>
<p>มีหลักในการใช้งานหลักน</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-built_in">range</span>(เริ่ม,จบ, การเพิ่มขึ้น)</code></pre>
</div>
<p><b>ตัวอย่างการใช้งาน range ใน Python</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-built_in">list</span>(<span class="hljs-built_in">range</span>(<span class="hljs-number">3</span>))
[<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>]</code></pre>
</div>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-built_in">list</span>(<span class="hljs-built_in">range</span>(<span class="hljs-number">0</span>,<span class="hljs-number">10</span>))
[<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>]</code></pre>
</div>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-built_in">list</span>(<span class="hljs-built_in">range</span>(-<span class="hljs-number">3</span>,<span class="hljs-number">9</span>))
[-<span class="hljs-number">3</span>, -<span class="hljs-number">2</span>, -<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>]</code></pre>
</div>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-built_in">list</span>(<span class="hljs-built_in">range</span>(<span class="hljs-number">0</span>, <span class="hljs-number">20</span>, <span class="hljs-number">2</span>))
[<span class="hljs-number">0</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>, <span class="hljs-number">10</span>, <span class="hljs-number">12</span>, <span class="hljs-number">14</span>, <span class="hljs-number">16</span>, <span class="hljs-number">18</span>]</code></pre>
</div>
<p><b>การนำไปใช้กับการลูป</b></p>
<p>สมมุติว่า มีโจทย์โปรแกรมให้เขียนโปรแกรมโดยใช้ for การลูปใน Python โดยไล่ตามนี้</p>
<p>1</p>
<p>22</p>
<p>333</p>
<p>4444</p>
<p>55555</p>
<p>โค้ดตัวอย่าง</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">1</span>, <span class="hljs-number">6</span>): <span class="hljs-comment">#กำหนดให้ตัวแปร i แทน range(1, 6) หมายถึงช่วงของตัวเลข 1 - 6</span>
<span class="hljs-built_in">print</span>(<span class="hljs-built_in">str</span>(i) * i + <span class="hljs-string">"\n"</span>)
<span class="hljs-number">1</span>
<span class="hljs-number">22</span>
<span class="hljs-number">333</span>
<span class="hljs-number">4444</span>
<span class="hljs-number">55555</span></code></pre>
</div>
<h2 id="บทที่-6-แยกข้อความด้วย-split-ใน-python-3">บทที่ 6 แยกข้อความด้วย split ใน Python 3</h2>
<p>การเขียนโปรแกรม เมื่อเรารับค่าข้อมูลมา โดยที่เราได้ทำกำหนดเครื่องหมายแยกข้อความ เช่น , - เป็นต้น<br />เมื่อต้องการแสดง หากต้องการแแสดงตัวแปรที่รับข้อมูลมาโดยมีการแยกข้อความมาแล้ว ใน Python เราต้องใช้ split</p>
<p>มีหลักการใช้งานดังนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code>ตัวแปร.split(<span class="hljs-string">"เครื่องหมายแยกข้อความที่กำหนด"</span>)</code></pre>
</div>
<p><b>ตัวอย่าง</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>a = <span class="hljs-string">u'สวัสดีปีใหม่ ขอให้มีแต่ความสุขกันนะครับ'</span>
a.split(<span class="hljs-string">" "</span>)</code></pre>
</div>
<p>ผลลัพธ์</p>
<div class="joplin-editable">
<pre class="hljs"><code>a = <span class="hljs-string">u'สวัสดีปีใหม่ ขอให้มีแต่ความสุขกันนะครับ'</span>
<span class="hljs-meta">>>> </span>a.split(<span class="hljs-string">" "</span>)
[<span class="hljs-string">'สวัสดีปีใหม่'</span>, <span class="hljs-string">'ขอให้มีแต่ความสุขกันนะครับ'</span>]</code></pre>
</div>
<p><b>ตัวอย่าง</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>b = <span class="hljs-string">"แมว,คน,นก"</span>
b.split(<span class="hljs-string">","</span>)</code></pre>
</div>
<p>ผลลัพธ์</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>b = <span class="hljs-string">"แมว,คน,นก"</span>
<span class="hljs-meta">>>> </span>b.split(<span class="hljs-string">","</span>)
[<span class="hljs-string">'แมว'</span>, <span class="hljs-string">'คน'</span>, <span class="hljs-string">'นก'</span>]</code></pre>
</div>
<h2 id="บทที่-7-input-การรับค่าข้อมูลจากคีย์บอร์ดใน-python">บทที่ 7 Input การรับค่าข้อมูลจากคีย์บอร์ดใน Python</h2>
<p>การรับค่าข้อมูล (Input) จากคีย์บอร์ดใน Python เป็นเรื่องพื้นฐานที่นักพัฒนาโปรแกรมไม่ว่าภาษาไหนก็ต้องเรียนรู้ด้วย<br />เมื่อตอน Python 2 มีคำสั่งรับค่าข้อมูลจากคีย์บอร์ดด้วยคำสั่ง</p>
<p><b>raw_input()</b></p>
<p>แต่ใน Python 3 ปัจจุบันนี้ได้มีการเปลี่ยนแปลงคำสั่งนิดหน่อยจาก</p>
<p><i><b>raw_input()</b></i></p>
<p>เป็น</p>
<p><i><b>input()</b></i></p>
<p>หากผู้อ่านเคยใช้ Python 2 เปลี่ยนมาใช้ Python 3 สามารถนำมาใช้งานง่าย ๆ แค่แก้ไขโค้ดนิดหน่อยสำหรับคำสั่งดังกล่าว</p>
<p><b>การรับค่า String ข้อความ ใน Python 3</b></p>
<p>ใช้ input() โดยมีรูปแบบการใช้งานดังน</p>
<div class="joplin-editable">
<pre class="hljs"><code>text = <span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter some text "</span>)</code></pre>
</div>
<p><b>การรับค่าตัวเลขจำนวนเต็มใน Python 3</b></p>
<p>ต้องใช้</p>
<p><b>int</b></p>
<p>มาใช้งานกับ</p>
<p><b>input()</b></p>
<p>เพื่อกำหนดให้รับค่าข้อมูลได้เฉพาะที่เป็นจำนวนเต็ม (-1 , 0 , 1) โดยใช้คำสั่ง</p>
<p><b>int(input())</b></p>
<p>โดยมีรูปแบบการใช้งานดังนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code>number = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter a integer: "</span>))</code></pre>
</div>
<p><b>การรับค่าเลขทศนิยมใน Python 3</b></p>
<p>ต้องใช้</p>
<p><b>float</b></p>
<p>มาใช้งานกับ</p>
<p><b>input()</b></p>
<p>เพื่อกำหนดให้รับค่าข้อมูลที่เป็นเลขทศนิยมได้ (-1.84 , 0.96 , 1.78) โดยใช้คำสั่ง</p>
<p><b>float(input())</b></p>
<p>โดยมีรูปแบบการใช้งานดังนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code>floating = <span class="hljs-built_in">float</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter a floating point number: "</span>))</code></pre>
</div>
<p>กรณีที่เขียนโปรแกรมโดยใช้คำสั่ง input() ไปแล้วต้องการแปลงค่าข้อมูลที่รับมาเป็นตัวเลขเพื่อนำไปคำนวณ เช่น</p>
<div class="joplin-editable">
<pre class="hljs"><code>number = <span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter some text "</span>) <span class="hljs-comment">#กำหนดตัวแปร number ให้รับค่าข้อมูล</span>
anumber = <span class="hljs-built_in">float</span>(number) <span class="hljs-comment">#เปลี่ยนข้อมูลที่รับมาในตัวแปร number ให้สามารถแปลงเป็น เลขทศนิยม</span>
<span class="hljs-comment">#เพื่อนำไปคำนวณได้ หากต้องการกำหนดให้เป็นจำนวณเต็มแค่เปลี่ยน float เป็น int</span></code></pre>
</div>
<h2 id="บทที่-8-การรับค่าตัวแปรและแสดงค่าตัวแปรใน-python-3">บทที่ 8 การรับค่าตัวแปรและแสดงค่าตัวแปรใน Python 3</h2>
<p>ทำไมต้องมีตัวแปร บทนิยมของตัวแปร คือ ลักษณะของข้อมูลที่เปลี่ยนแปลงได้ แสดงโดยใช้สัญลักษณ์ เช่น ตัวแปร X , Y ในเรื่องกราฟแกน X , Y ทางคณิตศาสตร์ เป็นต้น<br />ตัวแปรทำให้มีความง่ายต่อการเรียกใช้งานข้อมูล ถ้าจะเปรียบเทียบ ขอเปรียบเทียบแบบง่าย ๆ ตัวแปรก็เหมือนกับช่องว่างในกรอกข้อมูลในเอกสารต่าง ๆ</p>
<p><b>กฎการตั้งชื่อตัวแปรใน Python 3</b></p>
<ul><li>ห้ามตั้งชื่อตัวแปรให้ตรงกับคีย์เวิร์ดของ Python 3 โดยมีคีย์เวิร์ด ดังนี้ False class finally is return None continue for lambda try True def from nonlocal while and del global not with as elif if or yield assert else import pass break except in raise แต่สามารถใช้ตัวพิมพ์ใหญ่ได้</li><li>ห้ามใช้ตัวพิมพ์เล็ก</li><li>ห้ามใช้อักษระสัญลักษณ์ เช่น / * - + # ! - % $ เป็นต้น</li><li>ห้ามใช้ตัวเลข</li><li>ไม่เว้นว่าง</li></ul>
<p><b>รูปแบบการรับค่าตัวแปรใน Python 3</b><br />จะเป็นตัวเลขหรือข้อความก็ได้</p>
<blockquote>
<p>ตัวแปร = input()</p>
</blockquote>
<p>ตัวอย่างในรูปแแบบข้อความ เช่น</p>
<blockquote>
<p>name = input("What is your name? ")<br />แล้วรันจะได้ผลลัพท์ มีให้กรอกข้อความ<br />What is your name?</p>
</blockquote>
<p>สมมุติให้ผมกรอกว่า tonatn<br />What is your name? tontan</p>
<p>ตัวอย่างในรูปแบบตัวเลข</p>
<blockquote>
<p>a = int(input("input1: "))</p>
</blockquote>
<p><b>การแสดงค่าหรือดึงค่าจากตัวแปรมาใช้งานใน Python 3</b></p>
<blockquote>
<p>ตัวแปร</p>
</blockquote>
<p>ตัวอย่างเช่น</p>
<blockquote>
<p>name</p>
</blockquote>
<p>ก็จะแสดงผลลัพท์ค่าตัวแปร<br />'tontan'<br />หรือ print name<br />ก็แสดงค่าตัวแปรเช่นกัน</p>
<p><b>ตัวอย่างการเขียนโปรแกรมใน Python 3 โดยใช้ตัวแปรรวมด้วยโปรแกรมบวกเลข</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>a = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"input1: "</span>))
input1: <span class="hljs-number">1</span>
b = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"input1: "</span>))
input1: <span class="hljs-number">3</span>
<span class="hljs-built_in">print</span> (<span class="hljs-string">"="</span> , a + b)
= <span class="hljs-number">4</span></code></pre>
</div>
<h2 id="บทที่-9-คําสั่งเงื่อนไข-if-else-ใน-python-3">บทที่ 9 คำสั่งเงื่อนไข if else ใน Python 3</h2>
<p>บทความนี้จะพูดถึงเรื่อง คำสั่งเงื่อนไข if else ใน Python 3 กัน<br /><b>คำสั่งเงื่อนไข if</b><br />นี้ใช้ในการเปรียบเทียบเงื่อนไขว่าตรงตามที่ต้องการหรือไม่</p>
<p><b>คำสั่ง elif</b><br />ถ้าไม่ให้ทำการเปรียบเทียบต่อไป</p>
<p><b>คำสั่ง else</b></p>
<p>จนหมดเงื่อนไขที่จะเปรียบเทียบแล้วให้ทำตามคำสั่ง else</p>
<p>รูปแบบการใช้คำสั่งเงื่อนไข if else ใน Python 3</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">if</span> เงื่อนไข:
คำสั่ง
<span class="hljs-keyword">elif</span> เงื่อนไข:
คำสั่ง
<span class="hljs-keyword">else</span>:
คำสั่ง</code></pre>
</div>
<p><b>อธิบายรูปแบบการใช้คำสั่งเงื่อนไข if else ใน Python 3</b></p>
<p>เมื่อกำหนดเงื่อนไข if แล้ว ถ้าโปรแกรมที่สร้างนั้น<br />ต้องใช้เงื่อนไขหลายเงื่อนไขในการเปรียบเทียบ elif<br />โดยเปรียบเทียบเงื่อนไขไปเรื่อย ๆ จนกว่าเงื่อนไขไหนจะเป็นจริงจนสุดท้าย<br />ถ้าเงื่อนไขทั้งหมดเป็นเท็จ ให้ทำตามคำสั่งในเงื่อนไข else</p>
<p><b>ตัวอย่างการนำคำสั่งเงื่อนไข if else ไปใช้ในการเขียนโปรแกรมบน Python 3</b></p>
<p><b>ตัวอย่าง</b></p>
<p>โปรแกรมตรวจสอบตัวเลขว่าน้อยกว่ามากกว่าหรือเท่ากับ 0</p>
<p><b>หลักการโปรแกรม</b></p>
<p>รับค่าตัวเลขเข้ามาแล้วเอามาแทนตัวแปร x ให้ตัวแปร y = 0 เช็คว่า น้อยกว่ามากกว่าหรือเท่ากับ 0</p>
<p><b>โค้ด:</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>y = <span class="hljs-number">0</span>
x = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"input: "</span>))
<span class="hljs-keyword">if</span> x == y:
<span class="hljs-built_in">print</span> (<span class="hljs-string">"="</span> , y)
<span class="hljs-keyword">elif</span> x < y:
<span class="hljs-built_in">print</span> (<span class="hljs-string">"<"</span> , y)
<span class="hljs-keyword">elif</span> x > y:
<span class="hljs-built_in">print</span> (<span class="hljs-string">">"</span> , y)
<span class="hljs-keyword">else</span>:
<span class="hljs-built_in">print</span> (<span class="hljs-string">"No, It isn't num."</span>)</code></pre>
</div>
<h2 id="บทที่-10-ฟักชั่นทางคณิตศาสตร์เบี้องต้นใน-python-3">บทที่ 10 ฟักชั่นทางคณิตศาสตร์เบี้องต้นใน Python 3</h2>
<p>ฟักชั่นคณิตศาสตร์ถือเป็นสิ่งที่ขาดไม่ได้ในภาษาคอมพิวเตอร์ ฟักชั่นทางคณิตศาสตร์พื้นฐานก็จะมี + - * / เพื่อไม่เป็นการเสียมาเริ่มเนื้อหากันเลย</p>
<p><b>ฟักชั่นพื้นฐาน + - * / ** (บวก ลบ คูณ หาร ยกกำลัง) ใน Python 3</b><br />รูปแบบการใช้ ฟักชั่นพื้นฐาน + - * / ง่าย ๆ ดังนี้<br />บวก</p>
<blockquote>
<p>2 + 2<br />4<br />ลบ<br />50 - 5<br />45<br />คูณ<br />2 * 3<br />6<br />หาร<br />8 / 5<br />1.6</p>
</blockquote>
<p>แบบเงื่อนไข</p>
<blockquote>
<p>(2 + 2) * 5<br />20</p>
</blockquote>
<p>การยกกำลังใน Python 3</p>
<blockquote>
<p>2 ** 4<br />16</p>
</blockquote>
<p>ตัวอย่างการใช้ฟักชั่นทางคณิตศาสตร์โดยอ้างอิงตัวแปรใน Python 3</p>
<blockquote>
<p>a = 4<br />b = 3<br />(a + b) / a<br />1.75</p>
</blockquote>
<p>อีกตัวอย่างหนึ่ง ใช้ฟักชั่นทางคณิตศาสตร์เบี้องต้นในรูปแบบสมการ</p>
<blockquote>
<p>x = 3 + 4a<br />y = 2 - 3a<br />z = x + y<br />print(z)<br />(5+1a)</p>
</blockquote>
<h2 id="บทที่-11-คําสั่งการวงรอบ-loop-หรือคําสั่งทําซ้ํา">บทที่ 11 คำสั่งการวงรอบ Loop หรือคำสั่งทำซ้ำ</h2>
<p>การเขียนโปรแกรมในบางกรณีโปรแกรมที่เขียนต้องทำงานอย่างหนึ่ง ๆ ซ้ำกันหลาย ๆ ครั้ง เราต้องใช้การวงรอบ Loop ในการโปรแกรม<br />บทนี้จะนำเสนอการใช้คำสั่งการวงรอบ Loop ขอเรียกว่า คำสั่งทำซ้ำ</p>
<p>คำสั่งการวงรอบ Loop มีดังนี้</p>
<ul><li>for</li><li>while</li></ul>
<p>คำสั่งทำซ้ำ for ใน Python 3</p>
<p><b>รูปแบบ</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">for</span> ตัวแปร <span class="hljs-keyword">in</span> ลำดับขอบเขต :
คำสั่ง</code></pre>
</div>
<p><b>ตัวอย่างที่ 1</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">for</span> c <span class="hljs-keyword">in</span> <span class="hljs-string">'word'</span>:
<span class="hljs-built_in">print</span>( c )</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>w
o
r
d</code></pre>
</div>
<p><b>อธิบาย</b></p>
<p>กำหนดให้ตัวแปร c มีลำดับอยู่ใน word<br />(ถ้าเอาตามหลักคณิตศาสตร์ คือ เซต C มีสมาชิกเป็น w , o , r ,<br />d)แล้วแสดงสมาชิกที่อยู่ในขอบเขตนั้นออกมา</p>
<p><b>ตัวอย่างที่ 2</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">for</span> count <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">1</span>, <span class="hljs-number">11</span>):
<span class="hljs-built_in">print</span>(count)</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-number">1</span>
<span class="hljs-number">2</span>
<span class="hljs-number">3</span>
<span class="hljs-number">4</span>
<span class="hljs-number">5</span>
<span class="hljs-number">6</span>
<span class="hljs-number">7</span>
<span class="hljs-number">8</span>
<span class="hljs-number">9</span>
<span class="hljs-number">10</span></code></pre>
</div>
<p><b>อธิบาย</b></p>
<p>กำหนดให้ตัวแปร count มีลำดับในเงื่อนไข(1, 11) คือ ไล่ตัวเลขจาก 1 ถึง 10 ไม่เอา 11</p>
<p><b>ตัวอย่างที่ 3</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">3</span>):
<span class="hljs-built_in">print</span> (x)
<span class="hljs-keyword">else</span>:
<span class="hljs-built_in">print</span> (<span class="hljs-string">'Final x = %d'</span> % (x))</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-number">0</span>
<span class="hljs-number">1</span>
<span class="hljs-number">2</span>
Final x = <span class="hljs-number">2</span></code></pre>
</div>
<p><b>อธิบาย</b></p>
<p>กำหนดให้ x มีลำดับใน range(3) แล้วแสดงลำดับออกมา ต่อมาใช้ else แสดงลำดับสุดท้ายออกมา นั้นคือ 2</p>
<p><b>ตัวอย่างที่ 4</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>list_of_lists = [[<span class="hljs-string">"1, 2, 3"</span>], [<span class="hljs-string">"4, 5, 6"</span>], [<span class="hljs-string">"7, 8, 9"</span>]]
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> list_of_lists: <span class="hljs-comment"># loop รายการละ 1 รายการ</span>
<span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> i: <span class="hljs-comment"># loop รายการที่อยู่ในภายใน i ทีละ 1</span>
<span class="hljs-built_in">print</span> (x) <span class="hljs-comment"># แสดงผลรายการแต่ละอันที่อยู่ในรายการย่อยของรายการ i</span></code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>
<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>
<span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span></code></pre>
</div>
<p><b>อธิบาย</b></p>
<p>list อยู่ในลำดับของ list_of_lists แล้ว x อยู่ในลำดับของ list ให้แสดงลำดับนั้นออกมา</p>
<p><b>คำสั่งทำซ้ำ While ใน Python 3</b></p>
<p>คำสั่งทำซ้ำ While ใน Python<br />มีลักษณะการใช้เหมือนกันแต่จนกว่าเงื่อนไขที่กำหนดจะพบกัน เพราะการวนรอบใน<br />Python เพื่อให้มีประสิทธิภาพ While จึงนำมาใช้จำนวนน้อยครั้ง<br />ยกเว้นในกรณีที่มีการนำเข้าข้อมูลของผู้ใช้ที่จำเป็น</p>
<p><b>รูปแบบ</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">while</span> นิพจน์:
ข้อความสั่ง(s)</code></pre>
</div>
<p><b>ตัวอย่างที่ 5</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>count = <span class="hljs-number">0</span>
<span class="hljs-keyword">while</span> (count <= <span class="hljs-number">8</span>):
<span class="hljs-built_in">print</span> (<span class="hljs-string">'Is:'</span>, count)
count = (count + <span class="hljs-number">1</span>)</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>Is: <span class="hljs-number">0</span>
Is: <span class="hljs-number">1</span>
Is: <span class="hljs-number">2</span>
Is: <span class="hljs-number">3</span>
Is: <span class="hljs-number">4</span>
Is: <span class="hljs-number">5</span>
Is: <span class="hljs-number">6</span>
Is: <span class="hljs-number">7</span>
Is: <span class="hljs-number">8</span></code></pre>
</div>
<p><b>อธิบาย</b></p>
<p>กำหนดให้ตัวแปร x มีค่าเท่ากับ 0<br />แล้วต่อมาใช้คำสั่งทำซ้ำ While โดยในขณะที่ count น้อยกว่าหรือเท่ากับ 8<br />แล้วให้แสดงค่านั้นตามหลัง Is: แล้วให้ count + 1<br />แล้ววนรอบต่อไปจนกว่าจะเท่ากับ 8</p>
<p><b>ตัวอย่างที่ 6</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
n = <span class="hljs-built_in">input</span>(<span class="hljs-string">"Please enter 'hello':"</span>)
<span class="hljs-keyword">if</span> n.strip() == <span class="hljs-string">'hello'</span>:
<span class="hljs-keyword">break</span></code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>Please enter <span class="hljs-string">'hello'</span>:</code></pre>
</div>
<p><b>อธิบาย</b></p>
<p>กำหนดให้มีค่าความจริงเป็นจริง ให้ตัวแปร x<br />รับค่าจากผู้ใช้มาใช้ในเงื่อนไข if โดยค่าที่ได้จะเป็นจริงก็ต่อเมื่อค่า n<br />มีค่าเป็น hello เท่านั้นแล้วจึงจะออกจากการวนรอบโดยใช้ break</p>
<h2 id="บทที่-12-python-oop-อ๊อบเจ็กและคลาส">บทที่ 12 Python OOP อ๊อบเจ็กและคลาส</h2>
<p>หลาย ๆ ท่านคงเคยได้ยินคำว่า OOP การเขียนโปรแกรมเชิงวัตถุกันมาบ้างแล้ว โดย OOP ย่อมาจาก Object-Oriented Programming เป็นหลักการที่เหมาะสมกับการพัฒนาโปรแกรมทั้งขนาดเล็ก ขนาดกลาง และขนาดใหญ่</p>
<p>คลาสจะแบ่งปัญหาใหญ่ให้เล็กลงเพื่อแก้ไขในขอบเขตที่จำกัด บทนี้จะพาทุกท่านไปเขียน OOP ในภาษา Python กัน</p>
<p>มาเริ่มกันด้วยคลาสง่าย ๆ บน Python กัน</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">class</span> <span class="hljs-title class_">FC</span>:
<span class="hljs-keyword">pass</span></code></pre>
</div>
<p>ต่อมาสร้างอ๊อบเจ็ก</p>
<div class="joplin-editable">
<pre class="hljs"><code>a = FC()</code></pre>
</div>
<p>เราสามารถนำ a ไปใช้งานได้เลย เหมือนกล่องเปล่า</p>
<div class="joplin-editable">
<pre class="hljs"><code>a.one = <span class="hljs-number">1</span>
a.ten = <span class="hljs-number">10</span>
<span class="hljs-built_in">print</span> (a.ten - a.one)</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<p>9</p>
</blockquote>
<p>ตัวอย่างข้างบนมีข้อเสียตรงที่อ๊อบเจ็กอื่นของคลาส FC จะไม่มี one และ ten สามารถแก้ไขได้โดยการกำหนดค่าเริ่มต้น</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">class</span> <span class="hljs-title class_">FC</span>:
one = <span class="hljs-number">1</span>
ten = <span class="hljs-number">10</span></code></pre>
</div>
<p>เวลาเอาไปใช้</p>
<div class="joplin-editable">
<pre class="hljs"><code>a = FC.one
b = FC.ten
<span class="hljs-built_in">print</span> (b - a)</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<p>9</p>
</blockquote>
<p>ตัวอย่างข้างบน เป็นที่แน่นอนว่า คลาส FC มี one และ ten แน่นอน แต่ยังไม่สามารถกำหนดค่าเริ่มต้นแบบเป็นระเบียบได้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">class</span> <span class="hljs-title class_">FC</span>:
<span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self,one,ten</span>):
self.one = one
self.ten = ten</code></pre>
</div>
<p>วิธีกำหนดค่าเริ่มต้นจะต้องใช้ constructor เข้ามาช่วย นั้นคือเมธอดชื่อ<br /><b>init</b> ทุกเมธอดในคลาสจะใช้พารามิเตอร์ตัวแรกแทนตัวเอง<br />ชึ่งปกติจะใช้ชื่อ self สำหรับในภาษาซีหรือจาวา self คือ this</p>
<div class="joplin-editable">
<pre class="hljs"><code> a = FC(<span class="hljs-number">1</span>,<span class="hljs-number">10</span>)</code></pre>
</div>
<p>ต่อมาใส่เมธอดเพิ่มเติมเข้าไปในคลาส</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">class</span> <span class="hljs-title class_">FC</span>:
<span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self,one,ten</span>):
self.one = one
self.ten = ten
<span class="hljs-keyword">def</span> <span class="hljs-title function_">show</span>(<span class="hljs-params">self</span>):
<span class="hljs-built_in">print</span> (self.ten,<span class="hljs-string">"-"</span>,self.one,<span class="hljs-string">"="</span>,self.ten - self.one)</code></pre>
</div>
<p>นำมาใช้</p>
<div class="joplin-editable">
<pre class="hljs"><code>a = FC(one=<span class="hljs-number">1</span>,ten=<span class="hljs-number">10</span>)
a.show()</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<p>10 - 1 = 9</p>
</blockquote>
<h2 id="บทที่-13-python-regular-expressions">บทที่ 13 Python Regular Expressions</h2>
<p>Regular Expressions (RegEx) คือ วิธีการตรวจสอบข้อมูล โดยกำหนดรูปแบบของสตริงที่ต้องการตรวจสอบที่เรียกว่า แพตเทิร์น(Pattern) มีต้นกำเนิดมาจากภาษา Perl</p>
<p><b>รูปแบบแพตเทิร์น(Pattern) ใน Python</b></p>
<p><b>Anchors</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>^</code></pre>
</div>
<p>เริ่มต้นของสตริงหรือเริ่มต้นของบรรทัดในรูปแบบหลายบรรทัด</p>
<div class="joplin-editable">
<pre class="hljs"><code>\<span class="hljs-selector-tag">A</span></code></pre>
</div>
<p>จุดเริ่มต้นของสตริง</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-symbol">$</span></code></pre>
</div>
<p>สิ้นสุดของสตริงหรือจุดสิ้นสุดของเส้นในรูปแบบหลายบรรทัด</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-string">\Z</span></code></pre>
</div>
<p>สิ้นสุดของสตริง</p>
<div class="joplin-editable">
<pre class="hljs"><code>\<span class="hljs-selector-tag">b</span></code></pre>
</div>
<p>ขอบเขตคำ</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-addition">+</span></code></pre>
</div>
<p>ตรงกับอย่างน้อยหนึ่งอักขระก่อนหน้านี้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-comment">*</span></code></pre>
</div>
<p>มีหรือไม่ก็ได้</p>
<div class="joplin-editable">
<pre class="hljs"><code>|</code></pre>
</div>
<p>คือ "หรือ" , "OR"</p>
<p><b>haracter Classes</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>.</code></pre>
</div>
<p>(จุด) แทนตัวอักษรใด ๆ 1 ตัว ยกเว้นตัวอักษรขึ้นบรรทัดใหม่</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-string">\s</span></code></pre>
</div>
<p>เว้นบรรทัด</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-string">\S</span></code></pre>
</div>
<p>ไม่ได้เว้นบรรทัด</p>
<div class="joplin-editable">
<pre class="hljs"><code>\<span class="hljs-selector-tag">B</span></code></pre>
</div>
<p>ไม่ขอบเขตคำ</p>
<div class="joplin-editable">
<pre class="hljs"><code><</code></pre>
</div>
<p>จุดเริ่มต้นของคำ</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta prompt_">></span></code></pre>
</div>
<p>สุดท้ายของคำ</p>
<div class="joplin-editable">
<pre class="hljs"><code>\<span class="hljs-selector-tag">b</span></code></pre>
</div>
<p>ตรงกับขอบเขต string</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-string">\d</span></code></pre>
</div>
<p>แทนตัวเลข 0 ถึง 9</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-string">\D</span></code></pre>
</div>
<p>ตัวอักษรที่ไม่ใช่ตัวเลข</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-string">\w</span></code></pre>
</div>
<p>คำ</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-string">\W</span></code></pre>
</div>
<p>ไม่ใช่คำ</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-template-variable">{จำนวนที่ซ้ำ}</span></code></pre>
</div>
<p>ระบุว่าต้องการการซ้ำซ้อนทั้งหมดกี่ตัว</p>
<p><b>อักขระพิเศษ</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-string">\n</span></code></pre>
</div>
<p>บรรทัดใหม่</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-string">\t</span></code></pre>
</div>
<p>Tab</p>
<p><b>กลุ่ม</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>(<span class="hljs-name">?</span> ... )</code></pre>
</div>
<p>Passive (ไม่จับ) กลุ่ม</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-string">[abc]</span></code></pre>
</div>
<p>ช่วง (A หรือ B หรือ C)</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-string">[^abc]</span></code></pre>
</div>
<p>ไม่ใช่ a หรือ b หรือ c</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-string">[a-z]</span></code></pre>
</div>
<p>ใช้แทน a - z ตัวพิมพ์เล็ก</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-string">[a-z0-9]</span></code></pre>
</div>
<p>ใช้แทน a-z ตัวพิมพ์เล็กและแทนเลข 0 - 9</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-string">[A-Z]</span></code></pre>
</div>
<p>ใช้แทน A - Z ตัวพิมพ์ใหญ่</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-string">[A-Z0-9]</span></code></pre>
</div>
<p>ใช้แทน A - Z ตัวพิมพ์ใหญ่และแทนเลข 0 - 9</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-string">[0-9]</span></code></pre>
</div>
<p>ใช้แทนช่วง 0 - 9 ที่ยกมาด้านบนเป็นรูปแบบแพตเทิร์น(Pattern) ใน Python ที่ใช้กันบ่อย ๆ สำหรับเรื่อง รูปแบบแพตเทิร์น(Pattern) ไปศึกษารายละเอียดย่อย ๆ ได้ที่ <a data-from-md="" href="http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/" title="http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/">http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/</a></p>
<p>ในการใช้ Regular Expressions ใน Python เราต้องใช้โมดูลที่มากับตัว Python ที่มีชื่อว่า re</p>
<h3 id="findall">findall</h3>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-function"><span class="hljs-title">findall</span><span class="hljs-params">()</span></span></code></pre>
</div>
<p>เป็นฟังก์ชั่นที่มีประสิทธิภาพที่สุดในโมดูล re เราจะใช้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-function"><span class="hljs-title">findall</span><span class="hljs-params">()</span></span></code></pre>
</div>
<p>ในการค้นหารูปแบบในตัวอย่างนี้</p>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<p>['Barack Obama', 'Bill Gates']</p>
</blockquote>
<h3 id="match">match</h3>
<div class="joplin-editable">
<pre class="hljs"><code>re.<span class="hljs-keyword">match</span>()</code></pre>
</div>
<p>ตรวจสอบว่า Regular Expressions<br />ตรงที่จุดเริ่มต้นของสตริง เมื่อพบจะคืนค่า match object ออกมา<br />ถ้าไม่พบจะคืนค่า None ออกมา ดังตัวอย่างต่อไปนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> re
<span class="hljs-meta">>>> </span>m = p.<span class="hljs-keyword">match</span>(<span class="hljs-string">'tempo'</span>)
<span class="hljs-meta">>>> </span>m
<_sre.SRE_Match <span class="hljs-built_in">object</span>; span=(<span class="hljs-number">0</span>, <span class="hljs-number">5</span>), <span class="hljs-keyword">match</span>=<span class="hljs-string">'tempo'</span>></code></pre>
</div>
<p>ถ้าไม่พบข้อความ</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> re
<span class="hljs-meta">>>> </span>p.<span class="hljs-keyword">match</span>(<span class="hljs-string">""</span>)
<span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(p.<span class="hljs-keyword">match</span>(<span class="hljs-string">""</span>))
<span class="hljs-literal">None</span></code></pre>
</div>
<h3 id="search">search</h3>
<p>re.search() ใช้ค้นหารูปแบบภายในสตริงที่กำหนด ดังตัวอย่างต่อไปนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> re
<span class="hljs-built_in">print</span>(re.search(<span class="hljs-string">r'\d\d\d'</span>, <span class="hljs-string">'Your number is <b>123</b>'</span>).group(<span class="hljs-number">0</span>))</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<p>123</p>
<hr />
<p><b>การใช้ <code class="inline-code" spellcheck="false">re.search()</code> กับการเช็คเงื่อนไข if else</b></p>
<p>หากต้องการเช็คเงื่อนไข if else ว่าถ้าในสตริงมีรูปแบบที่ตรงกับรูปแบบ re<br />ที่กำหนดไว้ ให้ทำเงื่อนไขใน if หากไม่ใช่ ให้ทำเงื่อนไขใน else<br />สามารถทำได้โดยใช้โค้ดต่อไปนี้</p>
<p><b>ตัวอย่างเช่น</b></p>
<p>หากกำหนดรูปแบบให้ค้นหา 0 - 9 หากพบให้แสดงเป็น 1 หากไม่พบ ให้แสดงเป็น 0</p>
<p>เขียนรูปแบบ re ได้เป็น [0-9] ได้โค้ดออกมาตามตัวอย่างนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> re
a = <span class="hljs-string">'5'</span>
<span class="hljs-keyword">if</span> (re.search(<span class="hljs-string">r'[0-9]'</span>,a)):
<span class="hljs-built_in">print</span>(<span class="hljs-string">"1"</span>)
<span class="hljs-keyword">else</span>:
<span class="hljs-built_in">print</span>(<span class="hljs-string">"0"</span>)</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-number">1</span></code></pre>
</div>
<hr />
<h3 id="sub">sub</h3>
<p>re.sub() เป็นคำสั่งที่ใช้แทนที่ตัวอักษรในสตริง ไม่ว่าจะเป็นคำหรือประโยค ดังตัวอย่างต่อไปนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> re
a = <span class="hljs-string">"คน เดิน ด้วย เครื่องบิน"</span>
b = re.sub(<span class="hljs-string">"เดิน"</span>, <span class="hljs-string">"บิน"</span>, a)
<span class="hljs-built_in">print</span>(b)</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<p>คน บิน ด้วย เครื่องบิน</p>
</blockquote>
<h3 id="compile">compile</h3>
<div class="joplin-editable">
<pre class="hljs"><code>re.compile<span class="hljs-comment">()</span></code></pre>
</div>
<p>เป็นคำสั่งที่ใช้รวบรวมรูปแบบ (Pattern) เป็นวัตถุเก็บรูปแบบที่ต้องการ ดังตัวอย่างต่อไปนี้</p>
<blockquote>
<p>import re</p>
</blockquote>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<p>['hello', 'world']</p>
</blockquote>
<h3 id="split">split</h3>
<div class="joplin-editable">
<pre class="hljs"><code>re.<span class="hljs-built_in">split</span></code></pre>
</div>
<p>เป็นคำสั่งที่ใช้แยกสตริงตามที่กำหนด เราสามารถนำมาใช้ได้กับ Regular Expressions ดังตัวอย่างต่อไปนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> re
<span class="hljs-meta">>>> </span>re.split(<span class="hljs-string">'\W+'</span>,<span class="hljs-string">'This... is a test.'</span>)
[<span class="hljs-string">'This'</span>, <span class="hljs-string">'is'</span>, <span class="hljs-string">'a'</span>, <span class="hljs-string">'test'</span>, <span class="hljs-string">''</span>]</code></pre>
</div>
<p>สำหรับท่าใดที่อยากลองเขียน Regular Expressions ดู สามารถเข้าไปลองเขียนเล่นได้ที่ <a data-from-md="" href="https://re-try.appspot.com/" title="https://re-try.appspot.com/">http://re-try.appspot.com/</a></p>
<h2 id="บทที่-14-อ๊อบเจ็กและคลาสพื้นฐานในภาษา-python">บทที่ 14 อ๊อบเจ็กและคลาสพื้นฐานในภาษา Python</h2>
<p>ในภาษา Python การสร้างอ๊อบเจ็กและคลาส มีรูปแบบดังนี้</p>
<p>ลองเขียนอ๊อบเจ็กและคลาสกันดู</p>
<p>แล้วนำเรียกใช้ข้อมูลที่อยู่ในคลาส test</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>a = test() <span class="hljs-comment">#กำหนดให้ a แทนคำสั่งในคลาส test</span>
<span class="hljs-meta">>>> </span>a.run() <span class="hljs-comment">#เรียกใช้ฟังก์ชัน run ในคลาส test</span>
It<span class="hljs-string">'s ok
>>> a.opentest() #เรียกใช้ฟังก์ชัน opentest ในคลาส test
Open A Test</span></code></pre>
</div>
<p>จะเห็นได้ว่า เราสามารถเรียกใช้ฟังก์ชั่นที่อยู่ในคลาสได้<br />ด้วยการอ้างอิงตำแหน่งที่อยู่ของฟังก์ชั่นในคลาสนั้น<br />ต่อไปเราจะกำหนดให้ฟังก์ชั่นในคลาสสามารถกำหนดพารามิเตอร์ของฟังก์ชั่นได้ด้วยการใช้ self</p>
<p>แล้วลองนำมาใช้งานดู</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>b = test2() <span class="hljs-comment">#กำหนดให้ b แทนคำสั่งในคลาส test2</span>
<span class="hljs-meta">>>> </span>b.minus(<span class="hljs-number">10</span>,<span class="hljs-number">5</span>) <span class="hljs-comment">#เรียกใช้ฟังก์ชัน minus ในคลาส test2 โดยกำหนดพารามิเตอร์ num1,num2</span>
<span class="hljs-number">5</span></code></pre>
</div>
<p>หากเราต้องการกำหนดค่าเริ่มต้นจะต้องใช้ constructor เข้ามาช่วย นั้นคือเมธอดชื่อ <b>init</b> โดยทุกเมธอดในคลาสจะใช้พารามิเตอร์ตัวแรกแทนตัวมันเอง พูดง่าย ๆ ฟังก์ชั่นที่มีเมธอดชื่อ <b>init</b> จะเป็นฟังก์ชั่นหลักของคลาสนั้น</p>
<p>เมื่อเรียกใช้คลาส test3</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>c = test3(<span class="hljs-number">1</span>,<span class="hljs-number">2</span>)
<span class="hljs-number">3</span></code></pre>
</div>
<p>นอกจากนั้นเรายังสามารถเพิ่มฟังก์ชั่นลงในคลาสที่มีการใช้เมธอดชื่อ <b>init</b> ได้ด้วย</p>
<p>เรียกใช้งานในคลาส test4</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>aa = test4(<span class="hljs-number">2</span>,<span class="hljs-number">3</span>)
<span class="hljs-number">5</span>
<span class="hljs-meta">>>> </span>aa.test()
It<span class="hljs-string">'s ok</span></code></pre>
</div>
<p>เราสามารถกำหนดค่าว่างให้กับคลาสได้ด้วยคำสั่ง pass ตัวอย่างเช่น</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">class</span> <span class="hljs-title class_">D</span>():
<span class="hljs-keyword">pass</span></code></pre>
</div>
<p>เราสามารถใช้คลาส D โดยใช้เก็บค่าต่าง ๆ ได้เลย เหมือนเป็นกล่องเปล่า ตัวอย่างเช่น</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>a = D()
<span class="hljs-meta">>>> </span>a.one = <span class="hljs-number">1</span>
<span class="hljs-meta">>>> </span>a.ten = <span class="hljs-number">10</span>
<span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span> (a.ten - a.one)
<span class="hljs-number">9</span></code></pre>
</div>
<h3 id="คืนค่าข้อมูลด้วย-return">คืนค่าข้อมูลด้วย return</h3>
<p>คำสั่ง return เป็นคำสั่งสำหรับคืนคาข้อมูลที่อยู่ในคลาสและฟังก์ชัน</p>
<p><b>ตัวอย่างเช่น</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">def</span> <span class="hljs-title function_">ok</span>():
<span class="hljs-keyword">return</span> <span class="hljs-string">"ok"</span>
<span class="hljs-built_in">print</span>(ok)
<span class="hljs-built_in">print</span>(ok())</code></pre>
</div>
<p>ผลลัพธ์</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-attribute">ok</span></code></pre>
</div>
<h2 id="บทที่-15-สร้าง-modules-ใน-python-3">บทที่ 15 สร้าง Modules ใน Python 3</h2>
<p>ในบางกรณีเมื่อเราพัฒนาโปรแกรมโดยมีความซับซ้อนและมีขนาดใหญ่ ทำให้เราต้องเสียเวลาไปกับเขียนโค้ดเดิม ๆ ที่เรียกใช้และมีลักษณะการทำงานเหมือนกัน</p>
<p>หากเราเปลี่ยนมาใช้งานแบบ Modules ใน Python 3 จะช่วยเพิ่มความสะดวกสบายในเขียนโค้ดและเรียกใช้งานขึ้น</p>
<p>ใน Python เราแค่เขียนไฟล์ Modules ขึ้นมา แล้วบันทึก เวลาต้องการเรียกใช้งานแค่ import ชื่อไฟล์ Modules ที่สร้าง โดยไฟล์ Modules ที่สร้างต้องอยู่ในโฟลเดอร์เดียวกันกับไฟล์งานที่เรียกใช้</p>
<p><b>ตัวอย่างเช่น</b></p>
<p>ไฟล์ mod1.py</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">def</span> <span class="hljs-title function_">cal1</span>(<span class="hljs-params">a,b</span>):
c = a + b
<span class="hljs-keyword">return</span> c</code></pre>
</div>
<p>เป็นการสร้างฟังก์ชัน cal1 ขึ้นมา ทำเป็น Module เมื่อเรียกไปใช้งาน</p>
<p>ไฟล์ testmod1.py</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> firstmod
<span class="hljs-built_in">print</span> (firstmod.cal1(<span class="hljs-number">5</span>,<span class="hljs-number">6</span>))</code></pre>
</div>
<p>เรียกใช้งานฟังก์ชัน cal1 ใน Module ชื่อ firstmod จะได้ผลลัพธ์เป็น</p>
<blockquote>
<p>11</p>
</blockquote>
<p><b>ตัวอย่างต่อมา</b></p>
<p>ไฟล์ mod2.py</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">def</span> <span class="hljs-title function_">body</span>():
<span class="hljs-built_in">print</span> (<span class="hljs-string">"I'm Python. :)"</span>)</code></pre>
</div>
<p>เรียกมาใช้งาน</p>
<p>ไฟล์ testmod2.py</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> mod2
mod2.body()</code></pre>
</div>
<p>ได้ผลลัพธ์เป็น</p>
<blockquote>
<p>I'm Python. 😃</p>
</blockquote>
<h2 id="บทที่-16-ฟังก์ชัน-math-ใน-python">บทที่ 16 ฟังก์ชัน math ใน Python</h2>
<p>ฟังก์ชัน math เป็นฟังก์ชันที่ใช้คำนวณทางคณิตศาสตร์ เพื่อหาค่าทางคณิตศาสตร์ โดยฟังก์ชัน math ใน Python นี้จะใช้ฟังก์ชันทางคณิตศาสตร์ที่กำหนดโดยมาตรฐาน C</p>
<blockquote>
<p>เวลาเรียกใช้งานฟังก์ชัน math ใน Python ต้อง import math เข้ามาด้วย</p>
</blockquote>
<p><b>ทฤษฎีตัวเลข</b></p>
<ul><li>การปัดเลขทศนิยมmath.ceil(x)เมื่อแทน x เป็นจำนวนจริงเลขทศนิยมโค้ดตัวอย่าง math.ceil(0.54) แสดงผล 1</li><li>math.copysign(x, y)คืนค่าจำนวนจริงมีจำนวน (ค่าสัมบูรณ์) ของ x แต่เป็นเครื่องหมายของ y <code class="inline-code" spellcheck="false">math.copysign(1.0,-0.0)</code> ผลลัพธ์ <code class="inline-code" spellcheck="false">1.0</code></li><li>ค่าสัมบูรณ์math.fabs(x)คืนค่าสัมบูรณ์ของ xโค้ดตัวอย่าง<code class="inline-code" spellcheck="false">math.fabs(0.9)</code> ผลลัพธ์ <code class="inline-code" spellcheck="false">0.9</code></li><li>แฟกทอเรียล math.factorial(x) คืนค่า x แฟกทอเรียล เพิ่มค่าข้อผิดพลาดถ้า x ไม่เป็นจำนวนเต็มหรือเป็นจำนวนลบ</li></ul>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>math.factorial(<span class="hljs-number">5</span>)
<span class="hljs-number">120</span></code></pre>
</div>
<ul><li>ปัดเศษทศนิยมทิ้งmath.floor(x)คืนค่า x โดยปัดเศษทศนิยบนค่า X ทิ้ง</li></ul>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>math.floor(<span class="hljs-number">9.2</span>)
<span class="hljs-number">9</span></code></pre>
</div>
<ul><li>math.fmod(x,y)คืนค่าส่วนเหลือของ x หาร ด้วย y</li></ul>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>math.fmod(<span class="hljs-number">33</span>,<span class="hljs-number">55</span>)
<span class="hljs-number">33.0</span> <span class="hljs-comment">#หลังจากที่ 33/55 จะพบว่า เราไม่สามารถหารได้ถ้าไม่มีส่วนที่เหลือ คือ 33.0</span>
<span class="hljs-meta">>>> </span>math.fmod(<span class="hljs-number">10</span>,<span class="hljs-number">20</span>)
<span class="hljs-number">10.0</span></code></pre>
</div>
<ul><li>math.frexp(x)คืนค่าแมนทิสซา(mantissa)และเลขชี้กำลังของ x เป็นคู่ (m, e)</li></ul>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>math.frexp(<span class="hljs-number">16</span>)
(<span class="hljs-number">0.5</span>, <span class="hljs-number">5</span>)
<span class="hljs-meta">>>> </span>math.frexp(<span class="hljs-number">8</span>)
(<span class="hljs-number">0.5</span>, <span class="hljs-number">4</span>)</code></pre>
</div>
<ul><li>math.fsum(iterable)คืนค่าผลรวมของ iterable เช่น set, list, หรือ tuple</li></ul>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> math
<span class="hljs-meta">>>> </span>i=[<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">1</span>]
<span class="hljs-meta">>>> </span>math.fsum(i)
<span class="hljs-number">12.0</span></code></pre>
</div>
<ul><li>math.isfinite()คืนค่า true หรือ false ถ้าค่าของ x จะมีขอบเขต (เพิ่งมีใน Python 3.2)</li></ul>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>math.isfinite(<span class="hljs-number">12</span>**<span class="hljs-number">12</span>)
<span class="hljs-literal">True</span>
>>>math.isfinite(<span class="hljs-number">333</span>**<span class="hljs-number">55555553333445</span>)
false</code></pre>
</div>
<ul><li>math.isinf(x)คืนค่า True ถ้า x เป็นจำนวนเต็มบวกหรือเต็มลบที่เป็นจำนวนอนันต์ ถ้าไม่เป็นจำนวนอนันต์คืนค่า False</li><li>math.isnan(x)คืนค่า True ถ้า x ไม่ใช่จำนวนตัวเลข และคืนค่า False หากไม่ตรงกับเงื่อนไขนี้</li><li>math.ldexp(x, i)คืนค่า x * (2**i) คำสั่งนี้เป็นหลัก ผกผันของ ฟังก์ชัน frexp()</li><li>math.modf(x)คืนค่าส่วนที่เป็นจำนวนเต็มและเศษส่วนของ x ทั้งผลลัพธ์ดำเนินการเครื่องหมายของ x และเป็นจำนวนจริง</li><li>math.trunc(x)คืนค่าจริงของ x ถูกตัดเหลือเพียง Integral (มักจะเป็นจำนวนเต็ม ) ตัวแทน X__trunc__()</li></ul>
<p><b>Power และฟังก์ชั่นลอการิทึม</b></p>
<ul><li>math.exp(x)คืนค่า e**x</li><li>math.expm1(x)เพิ่งมีใน Python 3.2 เป็นต้นมาคืนค่า e**x - 1 ของจำนวนจริงขนาดเล็ก ในบวกการลบ exp(x) - 1 จะส่งผลต่อการสูญเสียความแม่นยำที่สำคัญไปฟังก์ชัน expm1() จะช่วยให้สามารถคำนวณปริมาณความแม่นยำเต็มรูปแบบนี้:</li></ul>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> exp, expm1
<span class="hljs-meta">>>> </span>exp(<span class="hljs-number">1e-5</span>) - <span class="hljs-number">1</span> <span class="hljs-comment">#ช่วยให้ผลลัพธ์ที่ถูกต้องถึง 11ตำแหน่ง</span>
<span class="hljs-number">1.0000050000069649e-05</span>
<span class="hljs-meta">>>> </span>expm1(<span class="hljs-number">1e-5</span>) <span class="hljs-comment"># ให้ผลลัพธ์ที่ถูกต้องแม่นยำกว่า exp()</span>
<span class="hljs-number">1.0000050000166668e-05</span></code></pre>
</div>
<ul><li>math.log(x[, เลขฐาน])คืนค่าผลลัพธ์ที่ได้จากค่า log ตามคณิตศาสตร์ หากไม่ได้กำหนดเลขฐาน เลขฐานจะเป็นค่า e</li></ul>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> math
<span class="hljs-meta">>>> </span>math.log(<span class="hljs-number">10</span>)
<span class="hljs-number">2.302585092994046</span>
<span class="hljs-meta">>>> </span>math.log(<span class="hljs-number">10</span>,<span class="hljs-number">10</span>)
<span class="hljs-number">1.0</span>
<span class="hljs-meta">>>> </span>math.log(<span class="hljs-number">2</span>)
<span class="hljs-number">0.6931471805599453</span>
<span class="hljs-meta">>>> </span>math.log(<span class="hljs-number">1</span>)
<span class="hljs-number">0.0</span>
<span class="hljs-meta">>>> </span>math.log(<span class="hljs-number">2</span>,<span class="hljs-number">2</span>)
<span class="hljs-number">1.0</span></code></pre>
</div>
<ul><li>math.log1p(x)คืนค่าลอการิทึมธรรมชาติของ 1 + x (ฐาน e) ผลลัพธ์การคำนวณที่ถูกต้องสำหรับ x อยู่ใกล้ศูนย์</li><li>math.log2(x)เพิ่งมีใน Python 3.3 เป็นต้นมาคืนค่าผลลัพธ์ที่ได้จากค่า log เลขฐาน 2 เหมือนใช้คำสั่ง log(x, 2)</li><li>math.log10(x)คืนค่าผลลัพธ์ที่ได้จากค่า log เลขฐาน 10 เหมือนใช้คำสั่ง log(x, 10)</li><li>math.pow(x, y)คืนค่าผลลัพธ์ที่ได้จากการที่ x ยกกำลัง y</li><li>math.sqrt(x)คืนค่ารากที่สองของ x</li></ul>
<p><b>ฟังก์ชันตรีโกณมิติ</b></p>
<ul><li>math.acos(x)คืนค่าอาร์กโคไซน์ (arccos หรือ cos-1) ของ x ในเรเดียน</li><li>math.asin(x)คืนค่า arc sine ของ x ในเรเดียน</li><li>math.atan(x)คืนค่า arc tan ของ x ในเรเดียน</li><li>math.atan2(y, x)คืนค่า atan(y / x) ของ x ในเรเดียน</li><li>math.cos(x)คืนค่า cosine ของ x ในเรเดียน</li><li>math.hypot(x, y)คืนค่าการคำนวณบรรทัดฐานแบบยุคลิด sqrt (x * x + y * y) นี้เป็นความยาวของเวกเตอร์จากแหล่งกำเนิดไปยังจุด (x, y)</li><li>math.sin(x)คืนค่า sin ของ x ในเรเดียน</li><li>math.tan(x)คืนค่า sin ของ x ในเรเดียน</li></ul>
<p><b>Angular conversion</b></p>
<ul><li>math.degrees(x)แปลงมุม x จากเรเดียนให้เป็นองศา</li><li>math.radians(x)แปลงมุม x จากองศาให้เป็นเรเดียน</li></ul>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> math
<span class="hljs-meta">>>> </span>math.radians(<span class="hljs-number">180</span>)
<span class="hljs-number">3.141592653589793</span>
<span class="hljs-meta">>>> </span>math.degrees(<span class="hljs-number">3.141592653589793</span>)
<span class="hljs-number">180.0</span></code></pre>
</div>
<p><b>Hyperbolic functions</b></p>
<ul><li>math.acosh(x) คืนค่าส่วนกลับ hyperbolic cosine ของ x</li><li>math.asinh(x) คืนค่าส่วนกลับ hyperbolic sine ของ x</li><li>math.atanh(x) คืนค่าส่วนกลับ hyperbolic tangent ของ x</li><li>math.cosh(x) คืนค่า hyperbolic cosine ของ x</li><li>math.sinh(x) คืนค่า hyperbolic sine ของ x</li><li>math.tanh(x) คืนค่า hyperbolic tangent ของ x</li></ul>
<p><b>ค่าคงตัว</b></p>
<ul><li>math.pi ค่าคงที่ทางคณิตศาสตร์ของ π = 3.141592...</li><li>math.e ค่าคงที่ทางคณิตศาสตร์ของ e = 2.718281...</li></ul>
<h2 id="บทที่-17-type-hints-ใน-python">บทที่ 17 Type hints ใน Python</h2>
<p>หลังจากที่ Python 3.5 ได้เปิดตัวออกมา ได้มีไวยากรณ์หนึ่งที่เพิ่มเข้ามาตั้งแต่ Python 3.5 นั่นคือ Type hints</p>
<p>Type hints คือ การบอกว่าฟังก์ชันหรือ method ต้องการตัวแปรชนิดใด และคืนค่าออกมาเป็นชนิดข้อมูลชนิดใด ช่วยให้เราสามารถเขียนโค้ดมีคุณภาพมากยิ่งขึ้น</p>
<p>ในภาษา Python ได้มีการเพิ่มการรองรับ type hints มาตั้งแต่ Python 3.5 เป็นต้นมา</p>
<p>สำหรับ Python ที่ต่ำกว่า 3.5 สามารถใช้งาน type hints โดย backport ด้วยคำสั่ง</p>
<div class="joplin-editable">
<pre class="hljs"><code>pip <span class="hljs-keyword">install</span> typing</code></pre>
</div>
<p><b>การใช้งาน <code class="inline-code" spellcheck="false">type hints</code></b></p>
<p>สมมติว่าต้องการสร้างฟังก์ชันบวกเลขด้วยข้อมูลชนิด int โดยที่ไม่ใช้ type hints</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">def</span> <span class="hljs-title function_">plus</span>(<span class="hljs-params">a,b</span>): <span class="hljs-keyword">return</span> a+b</code></pre>
</div>
<p>ผลลัพธ์</p>
<div class="joplin-editable">
<pre class="hljs"><code>plus(<span class="hljs-string">"9"</span>, <span class="hljs-string">"1"</span>)
<span class="hljs-string">"91"</span></code></pre>
</div>
<p>จะเห็นได้ว่า หากเป็น str บวกกันจะรวมข้อความกัน ทั้งที่เราอยากให้เฉพาะข้อมูล int เท่านั้นที่บวกกันได้ เพราะเราไม่ได้กำหนด method ว่าต้องการตัวแปรชนิดใด</p>
<p>เมื่อลองมาใช้ Type hints</p>
<p>การใช้ Type hints ทำได้ง่าย ๆ เพียงแค่เติม : หลังพารามิเตอร์แต่ละตัวแล้วใส่ชนิดข้อมูลที่ต้องการลงไป และใส่ -> ตามด้วยชนิดข้อมูลที่จะคืนค่าหลัง ) ดังนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">def</span> <span class="hljs-title function_">plus</span>(<span class="hljs-params">a: <span class="hljs-built_in">int</span>,b: <span class="hljs-built_in">int</span></span>)-><span class="hljs-built_in">int</span>: <span class="hljs-keyword">return</span> a+b</code></pre>
</div>
<p>หากลองรันจะรันได้ปกติ</p>
<div class="joplin-editable">
<pre class="hljs"><code>plus(<span class="hljs-string">"9"</span>, <span class="hljs-string">"1"</span>)
<span class="hljs-string">"91"</span></code></pre>
</div>
<p>แต่หากนำไปใช้ใน IDE อย่าง PyCharm จะมีการแจ้งเตือนหากใช้ข้อมูลผิดชนิดข้อมูลที่กำหนดไว้</p>
<h2 id="บทที่-18-recursive-function-กับ-python">บทที่ 18 Recursive Function กับ Python</h2>
<p>รีเคอร์ซีฟฟังก์ชัน (recursive functions) คือ ฟังก์ชันที่เรียกตัวเอง โดยแต่ละครั้งที่ฟังก์ชันถูกเรียก จะเกิดตัวแปรอัตโนมัติชุดใหม่ที่ไม่เกี่ยวข้องกับชุดเดิม จึงเรียกอีกชื่อหนึ่งว่า "ฟังก์ชันแบบเวียนเกิด"</p>
<p>หลักการรีเคอร์ซีฟฟังก์ชัน คือ เขียนโปรแกรมวนซ้ำเพื่อลดปัญหาของโปรแกรมที่ซับซ้อน</p>
<p>ขั้นตอนการเขียนรีเคอร์ซีฟฟังก์ชัน</p>
<ul><li>ทำความเข้าใจโจทย์</li><li>หาจุดวนกลับ โดยจะหาเมื่อการวนกลับยุติลงแล้วส่งค่ากลับไปคืนจุดที่เรียก</li><li>หาขั้นตอนที่ต้องเรียกซ้ำ</li></ul>
<p>รูปแบบทั่วไปของรีเคอร์ซีฟฟังก์ชันมีรูปแบบดังนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">def</span> <span class="hljs-title function_">ฟังกชัน</span>(<span class="hljs-params">พารามิเตอร์</span>):
<span class="hljs-keyword">if</span> < เงื่อนไขที่ผลให้ยุติการเรียกซ้ำ (จุดวกกลับ หรือ base <span class="hljs-keyword">case</span>) >:
ส่งคำตอบคืน
<span class="hljs-keyword">else</span>:
แยกปัญหาเป็นประเด็นย่อย ด้วยการเรียกซ้ำ (Recursive)</code></pre>
</div>
<blockquote>
<p>ข้อควรระวัง : ในการเขียนโปรแกรมด้วยรีเคอร์ซีฟฟังก์ชันต้องรอบคอบ และรีเคอร์ซีฟฟังก์ชันจำเป็นจะต้องมี if statement เพื่อตัดสินใจว่าควรเรียกตัวเองต่อไปหรือไม่</p>
</blockquote>
<p>ตัวอย่างเช่น โปรแกรม Python หาแฟกทอเรียลได้</p>
<p>โดยนิยามของแฟกทอเรียฟังก์ชัน คือ</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-built_in">n</span>! = <span class="hljs-built_in">n</span>*(<span class="hljs-built_in">n</span>-<span class="hljs-number">1</span>)! <span class="hljs-built_in">if</span> <span class="hljs-built_in">n</span> < <span class="hljs-number">0</span></code></pre>
</div>
<p>เอานำมาหา 5!</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-attribute">5</span>! = <span class="hljs-number">5</span>*<span class="hljs-number">4</span>*<span class="hljs-number">3</span>*<span class="hljs-number">2</span>*<span class="hljs-number">1</span> = <span class="hljs-number">5</span>*<span class="hljs-number">4</span>!
<span class="hljs-attribute">4</span>! = <span class="hljs-number">4</span>*<span class="hljs-number">3</span>*<span class="hljs-number">2</span>*<span class="hljs-number">1</span> = <span class="hljs-number">4</span>*<span class="hljs-number">3</span>!
<span class="hljs-attribute">3</span>! = <span class="hljs-number">3</span>*<span class="hljs-number">2</span>*<span class="hljs-number">1</span> = <span class="hljs-number">3</span>*<span class="hljs-number">2</span>!
<span class="hljs-attribute">2</span>! = <span class="hljs-number">2</span>*<span class="hljs-number">1</span> = <span class="hljs-number">2</span>*<span class="hljs-number">1</span>!
<span class="hljs-attribute">1</span>! = <span class="hljs-number">1</span> = <span class="hljs-number">1</span>
<span class="hljs-attribute">0</span>! = <span class="hljs-number">1</span> นี่คือ จุดวกกลับ หรือ base case</code></pre>
</div>
<p>สามารถเขียนโปรแกรม Python หาแฟกทอเรียลในรีเคอร์ซีฟฟังก์ชันได้ดังนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">def</span> <span class="hljs-title function_">factorial</span>(<span class="hljs-params">num</span>):
<span class="hljs-keyword">if</span> num==<span class="hljs-number">0</span>:
<span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
<span class="hljs-keyword">else</span>:
<span class="hljs-keyword">return</span> num * factorial(num-<span class="hljs-number">1</span>)
<span class="hljs-built_in">print</span>(factorial(<span class="hljs-number">3</span>))
<span class="hljs-built_in">print</span>(factorial(<span class="hljs-number">5</span>))</code></pre>
</div>
<p>ผลลัพธ์</p>
<div class="joplin-editable">
<pre class="hljs"><code>6
120</code></pre>
</div>
<p>ในทางกลับกัน เราสามารถนำรีเคอร์ซีฟฟังก์ชันมาเขียนเป็นฟังก์ชันลูปได้เช่นกัน</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">def</span> <span class="hljs-title function_">factorial</span>(<span class="hljs-params">num</span>):
i=num
<span class="hljs-keyword">while</span> num!=<span class="hljs-number">0</span>:
<span class="hljs-keyword">if</span> num!=<span class="hljs-number">1</span>:
i=i*(num-<span class="hljs-number">1</span>)
num-=<span class="hljs-number">1</span>
<span class="hljs-keyword">return</span> i
<span class="hljs-built_in">print</span>(factorial(<span class="hljs-number">3</span>))
<span class="hljs-built_in">print</span>(factorial(<span class="hljs-number">5</span>))</code></pre>
</div>
<p>ผลลัพธ์</p>
<div class="joplin-editable">
<pre class="hljs"><code>6
120</code></pre>
</div>
<p>เมื่อเปรียบเทียบระหว่างแบบรีเคอร์ซีฟฟังก์ชันกับแบบฟังก์ชันลูป<br />จะเห็นได้ว่า รีเคอร์ซีฟฟังก์ชันลดความซับซ้อนของโปรแกรมและเข้าใจง่ายขึ้น</p>
<p><b>ข้อควรระวังการใช้งานรีเคอร์ซีฟฟังก์ชัน</b></p>
<p>คือ ปัญหา Stack Overflow และในสถานการณ์ทั่วไป รีเคอร์ซีฟฟังก์ชันทำงานช้ากว่าลูป เพราะต้องเสียเวลาสร้าง Call Stack ในทุกครั้งที่เรียก</p>
<p>เมื่อนำรีเคอร์ซีฟฟังก์ชันไปสร้างเป็นไฟล์</p>
<div class="joplin-editable">
<pre class="hljs"><code>factorial1.<span class="hljs-keyword">py</span></code></pre>
</div>
<p>แล้วนำฟังก์ชันลูปไปสร้างเป็นไฟล์</p>
<div class="joplin-editable">
<pre class="hljs"><code>factorial2.<span class="hljs-keyword">py</span></code></pre>
</div>
<p>ทำการทดสอบด้วยโค้ด</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">python</span> -<span class="hljs-keyword">m</span> <span class="hljs-keyword">profile</span> ไฟล์.<span class="hljs-keyword">py</span></code></pre>
</div>
<p>ผลลัพธ์</p>
<p>ไฟล์ factorial1.py</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-attribute">6</span>
<span class="hljs-attribute">120</span>
<span class="hljs-attribute">16</span> function calls (<span class="hljs-number">8</span> primitive calls) in <span class="hljs-number">0</span>.<span class="hljs-number">007</span> seconds
<span class="hljs-attribute">Ordered</span> by: standard name
<span class="hljs-attribute">ncalls</span> tottime percall cumtime percall filename:lineno(function)
<span class="hljs-attribute">1</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> :<span class="hljs-number">0</span>(exec)
<span class="hljs-attribute">2</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> :<span class="hljs-number">0</span>(print)
<span class="hljs-attribute">1</span> <span class="hljs-number">0</span>.<span class="hljs-number">007</span> <span class="hljs-number">0</span>.<span class="hljs-number">007</span> <span class="hljs-number">0</span>.<span class="hljs-number">007</span> <span class="hljs-number">0</span>.<span class="hljs-number">007</span> :<span class="hljs-number">0</span>(setprofile)
<span class="hljs-attribute">1</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> factorial1.py:<span class="hljs-number">1</span>(<module>)
<span class="hljs-attribute">10</span>/<span class="hljs-number">2</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> factorial1.py:<span class="hljs-number">1</span>(factorial)
<span class="hljs-attribute">1</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">007</span> <span class="hljs-number">0</span>.<span class="hljs-number">007</span> profile:<span class="hljs-number">0</span>(<code object <module> at <span class="hljs-number">0</span>x7f1448cc08a0, file <span class="hljs-string">"factorial1.py"</span>, line <span class="hljs-number">1</span>>)
<span class="hljs-attribute">0</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> profile:<span class="hljs-number">0</span>(profiler)</code></pre>
</div>
<p>ไฟล์ factorial2.py</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-attribute">6</span>
<span class="hljs-attribute">120</span>
<span class="hljs-attribute">8</span> function calls in <span class="hljs-number">0</span>.<span class="hljs-number">005</span> seconds
<span class="hljs-attribute">Ordered</span> by: standard name
<span class="hljs-attribute">ncalls</span> tottime percall cumtime percall filename:lineno(function)
<span class="hljs-attribute">1</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> :<span class="hljs-number">0</span>(exec)
<span class="hljs-attribute">2</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> :<span class="hljs-number">0</span>(print)
<span class="hljs-attribute">1</span> <span class="hljs-number">0</span>.<span class="hljs-number">005</span> <span class="hljs-number">0</span>.<span class="hljs-number">005</span> <span class="hljs-number">0</span>.<span class="hljs-number">005</span> <span class="hljs-number">0</span>.<span class="hljs-number">005</span> :<span class="hljs-number">0</span>(setprofile)
<span class="hljs-attribute">1</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> factorial2.py:<span class="hljs-number">1</span>(<module>)
<span class="hljs-attribute">2</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> factorial2.py:<span class="hljs-number">1</span>(factorial)
<span class="hljs-attribute">1</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">005</span> <span class="hljs-number">0</span>.<span class="hljs-number">005</span> profile:<span class="hljs-number">0</span>(<code object <module> at <span class="hljs-number">0</span>x7f55e91108a0, file <span class="hljs-string">"factorial2.py"</span>, line <span class="hljs-number">1</span>>)
<span class="hljs-attribute">0</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> <span class="hljs-number">0</span>.<span class="hljs-number">000</span> profile:<span class="hljs-number">0</span>(profiler)</code></pre>
</div>
<p>จะเห็นได้ว่า ในภาษา Python รีเคอร์ซีฟฟังก์ชันทำงานช้ากว่าฟังก์ชันลูป และมีการเรียกใช้ function calls มากกว่า</p>
<h2 id="บทที่-19-ติดตั้งโมดูล-python-ด้วย-pip">บทที่ 19 ติดตั้งโมดูล python ด้วย pip</h2>
<p>pip เป็นคำสั่งสำหรับใช้ติดตั้งโมดูล Python ที่อยู่บน <a data-from-md="" href="http://pypi.org" title="http://pypi.org">pypi.org</a></p>
<p>PyPI ย่อมาจาก Python Package Index เป็นแหล่งรวมชุดคำสั่งของภาษา Python โดยทำงานร่วมกับคำสั่ง pip สำหรับติดตั้งชุดคำสั่งใน Python</p>
<p>ผู้ใช้งานสามารถค้นหาไลบรารีหรือโปรแกรมภาษา Python ได้ง่าย ๆ จากช่องค้นหา และมีรายละเอียดการคำสั่งติดตั้ง กับประวัติรุ่นไลบรารีที่ต้องการ</p>
<p>ส่วนสำหรับนักพัฒนาจะนำชุดคำสั่งภาษา Python ที่เขียน<br />ไม่ว่าจะเป็นไลบรารีหรือโปรแกรมต่าง ๆ ที่ใช้ร่วมกับภาษา Python<br />ขึ้นไปฝากไว้กับ PyPI โดย PyPI มีอยู่ 2 ส่วนด้วยกัน</p>
<ol><li>Test PyPI</li></ol>
<p>Test PyPI ตั้งอยู่ที่ <a data-from-md="" href="https://test.pypi.org/" title="https://test.pypi.org/">https://test.pypi.org/</a> ให้นักพัฒนาสามารถอัพโหลดไลบรารีหรือโปรแกรมภาษา Python ของตัวเองขึ้นทดสอบก่อนนำไปอัพโหลดขึ้น PyPI โดยการติดตั้งไลบรารีจาก Test PyPI จะใช้คำสั่งที่ยาวขึ้นมาหน่อยดังนี้</p>
<blockquote>
<p>pip install -i <a data-from-md="" href="https://test.pypi.org/simple/" title="https://test.pypi.org/simple/">https://test.pypi.org/simple/</a> ชื่อไลบรารี</p>
</blockquote>
<ol start="2"><li>PyPI</li></ol>
<p>PyPI ตั้งอยู่ที่ <a data-from-md="" href="https://pypi.org/" title="https://pypi.org/">https://pypi.org/</a> ผู้ใช้งานสามารถติดตั้งไลบรารีหรือโปรแกรมโปรแกรมภาษา Python ได้ หากว่านักพัฒนาอัพโหลดไลบรารีหรือโปรแกรมของตัวเองขึ้น PyPI แล้ว<br />เพียงแค่ใช้คำสั่ง</p>
<blockquote>
<p>pip install ไลบรารี</p>
</blockquote>
<p><b>คำสั่งที่ควรรู้</b></p>
<ul><li>pip install package - เป็นคำสั่งติดตั้งโมดูล</li><li>pip uninstall package - เป็นคำสั่งถอนการติดตั้งโมดูล (ต้องยืนยันก่อนถอนด้วย)</li></ul>
<h2 id="บทที่-19-เขียนไฟล์-อ่านไฟล์ด้วยภาษา-python">บทที่ 19 เขียนไฟล์-อ่านไฟล์ด้วยภาษา Python</h2>
<p>บทนี้เราจะมาเรียนรู้กับการอ่าน เขียน ไฟล์บนภาษา Python</p>
<h3 id="เขียนและอ่านข้อมูลจากเท็กซ์ไฟล์บน-python-3">เขียนและอ่านข้อมูลจากเท็กซ์ไฟล์บน Python 3</h3>
<p>เท็กซ์ไฟล์ (Text Files) เป็นอีกหนึ่งรูปแบบในการบันทึกข้อมูล</p>
<p><b>มาเริ่มต้นที่การเปิดไฟล์กัน</b></p>
<p>รูปแบบการเปิดไฟล์</p>
<blockquote>
<p>ตัวแปร = open(ชื่อไฟล์, โหมดการเปิดไฟล์)</p>
</blockquote>
<p><b>โหมดการเปิดไฟล์ที่ใช้กับเท็กซ์ไฟล์</b></p>
<p>r คือ อ่านเพียงอย่างเดียว</p>
<p>w คือ เขียนเพียงอย่างเดียว ถ้ายังไม่มีไฟล์ จะสร้างไฟล์ใหม่</p>
<p>w+ คือ เขียน สร้างไฟล์ใหม่ หรือแทนที่ข้อมูลเดิม</p>
<p>a คือ เปิดไฟล์แล้วเขียนข้อมูลต่อท้ายข้อมูลเดิม</p>
<p>r+ คือ เปิดไฟล์เพื่ออ่านหรือเขียนข้อมูลทับไฟล์</p>
<p><b>ตัวอย่าง</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>a = <span class="hljs-built_in">open</span>(<span class="hljs-string">'work1.txt'</span>, <span class="hljs-string">'w'</span>)</code></pre>
</div>
<p><b>เขียนข้อมูลลงเท็กซ์ไฟล์</b></p>
<p>สำหรับโหมดเขียนข้อมูลลงไฟล์นี้ ห้ามใช้ r เพราะโหมดนี้ไม่สามารถเขียนข้อมูลลงไฟล์ได้</p>
<p>มีรูปแบบดังนี้</p>
<blockquote>
<p>ตัวแปรที่เปิดไฟล์.write(ข้อความหรือตัวแปร)</p>
</blockquote>
<p><b>ตัวอย่าง</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>a = <span class="hljs-built_in">open</span>(<span class="hljs-string">'work1.txt'</span>, <span class="hljs-string">'w'</span>)
a.write(<span class="hljs-string">'This is a testn'</span>)</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<p>work1.txt</p>
<blockquote>
<p>This is a testn</p>
</blockquote>
<p>เขียน<b>ข้อมูลรายการ (List) ลงเท็กซ์ไฟล์ทีละบรรทัด</b></p>
<p>มีรูปแบบดังนี้</p>
<blockquote>
<p>ตัวแปรที่เปิดไฟล์.writelines(List ข้อมูล)</p>
</blockquote>
<p><b>อ่านข้อมูลจากเท็กซ์ไฟล์</b></p>
<p>มีรูปแบบดังนี้</p>
<blockquote>
<p>ตัวแปรที่เปิดไฟล์.read()</p>
</blockquote>
<p><b>ตัวอย่าง</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>a = <span class="hljs-built_in">open</span>(<span class="hljs-string">'work1.txt'</span>, <span class="hljs-string">'r'</span>)
a.read()</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<p>This is a testn</p>
</blockquote>
<p><b>หรือจะใช้ with</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(<span class="hljs-string">'work1.txt'</span>, <span class="hljs-string">'r'</span>) <span class="hljs-keyword">as</span> f:
read_data = f.read()
<span class="hljs-built_in">print</span>(read_data)</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<p>This is a testn</p>
</blockquote>
<p><b>อ่านข้อมูลจากเท็กซ์ไฟล์ทีละบรรทัด</b></p>
<p>ในการอ่านข้อมูลทีละบรรทัดนี้ Python ได้แบ่งบรรทัดโดยอ้างอิง <code class="inline-code" spellcheck="false">\n</code><br />เวลาเขียนข้อมูลลงไฟล์ หากต้องการขึ้นบรรทัดใหม่ให้ใส่ <code class="inline-code" spellcheck="false">\n</code> ตามหลังเข้าไปด้วย</p>
<p>มีรูปแบบดังนี้</p>
<blockquote>
<p>ตัวแปรที่เปิดไฟล์.readline()</p>
</blockquote>
<p><b>ตัวอย่าง</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>a = <span class="hljs-built_in">open</span>(<span class="hljs-string">'work2.txt'</span>, <span class="hljs-string">'r'</span>)
a.readline()</code></pre>
</div>
<p><b>ปิดไฟล์หลังเรียกใช้งาน</b></p>
<p>เมื่อเรียกใช้งานไฟล์เสร็จ ควรที่จะปิดไฟล์เพื่อคืนทรัพยากรให้กับระบบ</p>
<p>มีรูปแบบการใช้งานดังนี้</p>
<blockquote>
<p>ตัวแปรที่เปิดไฟล์.close</p>
</blockquote>
<p><b>ตัวอย่าง</b></p>
<blockquote>
<p>a.close()</p>
</blockquote>
<p><b>ฟังก์ชันเพิ่มเติม</b></p>
<ul><li>ตัวแปรที่เปิดไฟล์.name - จะคืนค่าชื่อไฟล์ที่เปิดอยู่</li><li>ตัวแปรที่เปิดไฟล์.mode - จะคืนค่าโหมดการเปิดไฟล์ เช่น w , r เป็นต้น</li></ul>
<h3 id="อ่าน-เขียนข้อมูลไบนารีไฟล์ในภาษาไพทอน">อ่าน-เขียนข้อมูลไบนารีไฟล์ในภาษาไพทอน</h3>
<p>ไบนารีไฟล์ (binary files) เป็นไฟล์ข้อมูลในรูปแบบเฉพาะของคอมพิวเตอร์ โดยข้อมูลที่เก็บอาจเป็นเลขจำนวนเต็ม ตัวอักษร และอื่น ๆ เป็นต้น</p>
<p>ในภาษาไพทอน มีหลักไวยากรณ์ในการอ่านและเขียนข้อมูลไบนารีไฟล์ในภาษาไพทอนดังนี้</p>
<p><b>การเปิดไฟล์ไบนารีในภาษาไพทอน</b></p>
<blockquote>
<p>open(ชื่อไฟล์,โหมดการเปิดไฟล์)</p>
</blockquote>
<p>โหมดการเปิดไฟล์มีดังนี้</p>
<ul><li>wb เขียนไบนารีไฟล์หรือสร้างไบนารีไฟล์ใหม่ในกรณีที่ไม่มีไฟล์ที่เรียก</li><li>rb อ่านไบนารีไฟล์</li><li>ab เขียนข้อมูลต่อท้ายข้อมูลที่มีอยู่ในไฟล์</li><li>wb+ เขียนไบนารีไฟล์หรือสร้างไบนารีไฟล์ใหม่ในกรณีที่ไม่มีไฟล์ที่เรียก</li><li>rb+ อ่านไบนารีไฟล์ ถ้าไม่มีไฟล์ให้สร้างไฟล์ใหม่</li><li>ab+ เขียนข้อมูลต่อท้ายข้อมูลที่มีอยู่ในไฟล์ ถ้าไม่มีไฟล์ให้สร้างไฟล์ใหม่</li></ul>
<p><b>การปิดไฟล์</b></p>
<p>หลังอ่าน เขียน ไฟล์แล้ว เพื่อคืนความจำให้กับระบบ ต้องทำการปิดไฟล์ โดยใช้คำสั่ง</p>
<blockquote>
<p>file.close()</p>
</blockquote>
<p><b>เขียนข้อมูลลงไฟล์</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>ทบทวนความรู้พื้นฐานเรื่องจำนวนไบต์และบิต MB GB
<span class="hljs-number">8</span> Bit <span class="hljs-comment">(บิต)</span> = <span class="hljs-number">1</span> Byte <span class="hljs-comment">(ไบต์)</span>
<span class="hljs-number">1</span> Byte <span class="hljs-comment">(ไบต์)</span> = <span class="hljs-number">1</span> ตัวอักษร
<span class="hljs-number">1</span> KB <span class="hljs-comment">(กิโลไบต์)</span> = <span class="hljs-number">1024</span> Byte
<span class="hljs-number">1</span> MB <span class="hljs-comment">(เมกกะไบต์)</span> = <span class="hljs-number">1024</span> KB
<span class="hljs-number">1</span> GB <span class="hljs-comment">(กิกะไบต์)</span> = <span class="hljs-number">1024</span> MB</code></pre>
</div>
<p>การเขียนข้อมูลลงไบนารีไฟล์ในภาษาไพทอน ใช้คำสั่งต่อไปนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code>file.write(ข้อมูลไบต์)</code></pre>
</div>
<p><b>ตัวอย่างการเขียนข้อมูลลงไฟล์</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>ofile = <span class="hljs-built_in">open</span>(<span class="hljs-string">"a"</span>, <span class="hljs-string">'wb'</span>) <span class="hljs-comment"># wb เขียนไฟล์</span>
ofile.write(<span class="hljs-string">b"ok"</span>)
ofile.close()</code></pre>
</div>
<p><b>เขียนข้อมูลต่อจากไฟล์เดิม</b></p>
<p>ใช้โหมดเปิดไฟล์ ab</p>
<p>ตัวอย่าง</p>
<div class="joplin-editable">
<pre class="hljs"><code>ofile = <span class="hljs-built_in">open</span>(<span class="hljs-string">"a"</span>, <span class="hljs-string">'ab'</span>) <span class="hljs-comment"># ab เขียนข้อมูลต่อจากไฟล์เดิม</span>
ofile.write(<span class="hljs-string">b"Hi"</span>)
ofile.close()</code></pre>
</div>
<p><b>อ่านไฟล์</b></p>
<p>ใช้คำสั่ง</p>
<div class="joplin-editable">
<pre class="hljs"><code>file.read(ขนาดข้อมูลไบต์ที่อ่าน)</code></pre>
</div>
<p><b>ตัวอย่างการอ่านไฟล์</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>ofile = <span class="hljs-built_in">open</span>(<span class="hljs-string">"a"</span>, <span class="hljs-string">'rb'</span>) <span class="hljs-comment"># rb อ่านไฟล์</span>
<span class="hljs-built_in">print</span>(ofile.read(<span class="hljs-number">2</span>)) <span class="hljs-comment"># อ่านข้อมูล 2 ไบต์</span>
<span class="hljs-built_in">print</span>(ofile.read(<span class="hljs-number">2</span>)) <span class="hljs-comment"># อ่านข้อมูลอีก 2 ไบต์</span>
ofile.close() <span class="hljs-comment"># ปิดไฟล์</span></code></pre>
</div>
<p>ผลลัพธ์</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-string">b'ok'</span>
<span class="hljs-string">b'Hi'</span></code></pre>
</div>
<h2 id="บทที่-20-สร้างโมดูลพร้อมใช้ให้คอมเครื่องอื่น">บทที่ 20 สร้างโมดูลพร้อมใช้ให้คอมเครื่องอื่น</h2>
<p>หลักการเรียกใช้โมดูลในโฟลเลอร์เดียวกัน</p>
<p>ในการ import เรียกใช้โมดูลในโฟลเลอร์เดียวกัน สามารถทำได้โดยตามตัวอย่างนี้<br />hello.py</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-built_in">print</span>(<span class="hljs-string">"Hello"</span>)
</code></pre>
</div>
<p>เราสร้างตัวโมดูลสำหรับเรียกใช้กันในโฟลเลอร์เดียวกันแล้ว สามารถเรียกใช้ได้เลยโดยใช้การ</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> ชื่อไฟล์โมดูล
</code></pre>
</div>
<p>โดยชื่อไฟล์โมดูลไม่ต้องมี .py ตัวอย่างเช่น<br /><a data-from-md="" href="http://show.py/" title="http://show.py/">show.py</a></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> hello
</code></pre>
</div>
<p>ผลลัพธ์</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-attribute">Hello</span>
</code></pre>
</div>
<p>หากเราต้องการให้มีการเรียกใช้คำสั่งที่อยู่ในโมดูล เราต้องสร้างฟังก์ชันขึ้นมารองรับด้วย เมื่อเรียกใช้งาน โดยอ้างอิงจากฟังก์ชันที่อยู่ใน cal.py</p>
<p>test.py</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">from</span> cal <span class="hljs-keyword">import</span> plue,plueto <span class="hljs-comment">#เรียกใช้ฟังก์ชันหรือ class จากโมดูล cal</span>
<span class="hljs-built_in">print</span>(plue(<span class="hljs-number">5</span>))
<span class="hljs-built_in">print</span>(plueto(<span class="hljs-number">5</span>,<span class="hljs-number">10</span>))
</code></pre>
</div>
<p>ผลลัพธ์</p>
<div class="joplin-editable">
<pre class="hljs"><code>10
15</code></pre>
</div>
<p>หากเราต้องการทราบคำสั่งที่อยู่ในโมดูล cal ที่เราเขียนขึ้นมา สามารถใช้คำสั่ง <b>dict</b>.keys() ได้ดังนี้<br />list.py</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> cal
<span class="hljs-built_in">print</span>(cal.__dict__.keys())</code></pre>
</div>
<p>ผลลัพธ์</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-function"><span class="hljs-title">dict_keys</span><span class="hljs-params">([<span class="hljs-string">'__builtins__'</span>, <span class="hljs-string">'plueto'</span>, <span class="hljs-string">'__name__'</span>, <span class="hljs-string">'__doc__'</span>, <span class="hljs-string">'plue'</span>, <span class="hljs-string">'__spec__'</span>, <span class="hljs-string">'__file__'</span>, <span class="hljs-string">'__loader__'</span>, <span class="hljs-string">'__cached__'</span>, <span class="hljs-string">'__package__'</span>])</span></span>
</code></pre>
</div>
<p>ในกรณีที่มีคำสั่งในโมดูลที่เราเขียน หากเราต้องการสร้าง main ขึ้นมา (เหมือนภาษา C) โดยจะเรียกใช้งานได้เฉพาะโค้ดนี้เท่านั้น เราสามารถใช้ <b>name</b> == '<b>main</b>' ได้ตามน<br />caltwo.py</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
<span class="hljs-built_in">print</span>(<span class="hljs-string">"5"</span>)</code></pre>
</div>
<p>เมื่อเรา import โมดูลเข้ามา<br />show2.py</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> caltwo</code></pre>
</div>
<p>ผลลัพธ์<br />จะพบว่า ไม่มีอะไรขึ้นมาเพราะ show2.py ไม่ใช่โปรแกรมหลัก</p>
<h3 id="ทําไฟล์ติดตั้งโมดูลใน-python">ทำไฟล์ติดตั้งโมดูลใน Python</h3>
<p>หลังจากที่ได้พาผู้อ่านไปเรียกใช้โมดูลในโฟลเลอร์เดียวกันมาแล้ว ต่อไปเราจะทำให้สามารถเรียกใช้งานโมดูลได้โดยที่ไม่ต้องเป็นต้องอยู่โฟลเลอร์เดียวกันกับไฟล์โมดูล เหมือนเราเรียกใช้โมดูล lxml , pyside โดยมีตัวอย่างต่อไปนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">from</span> distutils.core <span class="hljs-keyword">import</span> setup <span class="hljs-comment">#ระบบติดตั้งโมดูล</span>
setup(name=<span class="hljs-string">'Distutils'</span>, <span class="hljs-comment">#ชื่อโมดูล</span>
version=<span class="hljs-string">'1.0'</span>, <span class="hljs-comment">#เวชั่นของโมดูล</span>
description=<span class="hljs-string">'Python Distribution Utilities'</span>, <span class="hljs-comment">#รายละเอียดโมดูล</span>
author=<span class="hljs-string">'Greg Ward'</span>, <span class="hljs-comment">#ชื่อผู้สร้างโมดูล</span>
author_email=<span class="hljs-string">'gward@python.net'</span>, <span class="hljs-comment">#อีเมลล์ติดต่อผู้สร้างโมดูล</span>
url=<span class="hljs-string">'https://www.python.org/sigs/distutils-sig/'</span>, <span class="hljs-comment">#หน้าเว็บโมดูล</span>
packages=[<span class="hljs-string">'distutils'</span>], <span class="hljs-comment">#packages ที่ถูกรวมด้วย โดย packages คือโฟลเลอร์ที่ใช้เก็บไฟล์โมดูลของเรา</span>
)</code></pre>
</div>
<p>ต่อไปลงมือทำโมดูลกัน โดยนำไฟล์ cal.py มาทำเป็นโมดูล โดยมีโค้ดดังต่อไป</p>
<p><b>cal.py</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">def</span> <span class="hljs-title function_">plue</span>(<span class="hljs-params">arg</span>):
<span class="hljs-keyword">return</span> arg+arg
<span class="hljs-keyword">def</span> <span class="hljs-title function_">plueto</span>(<span class="hljs-params">a,b</span>):
<span class="hljs-keyword">return</span> a+b</code></pre>
</div>
<p>สร้างโฟลเลอร์ใหม่ แล้วเก็บไฟล์ cal.py ไว้ในโฟลเลอร์ packages ที่เราสร้างขึ้นมาเพิ่มชื่อว่า cal</p>
<p><b>รายละเอียดระบบไฟล์ของโมดูล</b></p>
<div class="joplin-editable">
<pre class="hljs"><code>โฟลเลอร์หลัก\
<span class="hljs-keyword">cal</span>\
__init__.<span class="hljs-keyword">py</span>
<span class="hljs-keyword">cal</span>.<span class="hljs-keyword">py</span>
setup.<span class="hljs-keyword">py</span></code></pre>
</div>
<p>และผมสร้างไฟล์ <b>init</b>.py เป็นไฟล์สำหรับกำหนดค่าการเรียกใช้คำสั่งในโมดูล</p>
<p><b><b>init</b>.py</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">from</span> cal <span class="hljs-keyword">import</span> * <span class="hljs-comment"># หมายถึงเรียกใช้โมดูลจากไฟล์ cal.py ที่อยู่ในโฟลเลอร์เดียวกัน โดยดึงคำสั่งทุกคำสั่งมา</span></code></pre>
</div>
<p>เสร็จแล้วทำไฟล์ setup.py ซึ่งเป็นไฟล์ระบบล์ติดตั้งโมดูล โดยไว้ในโฟลเลอร์หลัก</p>
<p>โดยโค้ดไฟล์ setup.py มีดังนี้</p>
<p><b>setup.py</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">from</span> distutils.core <span class="hljs-keyword">import</span> setup
setup(
name=<span class="hljs-string">'cal'</span>,
version=<span class="hljs-string">'0.0.1'</span>,
author=<span class="hljs-string">'Wannaphong'</span>,
packages=[<span class="hljs-string">'cal'</span>],
url=<span class="hljs-string">'https://python3.wannaphong.com'</span>,
license=<span class="hljs-string">'MIT'</span>, <span class="hljs-comment">#license</span>
description=<span class="hljs-string">'Test'</span>,
include_package_data=<span class="hljs-literal">True</span>,
)</code></pre>
</div>
<p>แล้วเปิดคอมมานด์ไลน์ทำการติดตั้งโมดูลที่ผมทำขึ้นมาเอง</p>
<blockquote>
<p>python setup.py install</p>
</blockquote>
<p>เสร็จแล้วลองรันใช้งานใน Python IDE ดู</p>
<blockquote>
<blockquote>
<blockquote>
<blockquote>
<p>from cal import cal</p>
</blockquote>
</blockquote>
</blockquote>
</blockquote>
<p>อ่านรายละเอียดของการทำไฟล์ติดตั้งโมดูลใน Python ได้ที่</p>
<p><a data-from-md="" href="https://docs.python.org/3/distutils/setupscript.html" title="https://docs.python.org/3/distutils/setupscript.html">https://docs.python.org/3/distutils/setupscript.html</a></p>
<h3 id="ส่งโมดูล-python-ขึ้นไปยัง-pypi">ส่งโมดูล Python ขึ้นไปยัง PyPI</h3>
<p><b>PyPI คืออะไร</b></p>
<p>PyPI ย่อมาจาก Python Package Index เป็นคลังโปรแกรมและไลบรารีเสริมของ Python โดย Python เวชั่นใหม่ ๆ สามารถสั่งติดตั้งโมดูลจาก PyPI<br />ได้ด้วยคำสั่ง pip หรือคำสั่ง easy_install ได้</p>
<p>อย่างแรกให้ผู้อ่านสมัคร PyPI account สำหรับส่งโมดูลขึ้นไปยัง PyPI ได้ที่</p>
<p><a data-from-md="" href="https://pypi.python.org/pypi?%3Aaction=register_form" title="https://pypi.python.org/pypi?%3Aaction=register_form">https://pypi.python.org/pypi?%3Aaction=register_form</a></p>
<p>โดยต้องใช้ PGP Key ID ด้วย อ่านวิธีการทำ PGP Key ID ได้ที่ <a data-from-md="" href="https://www.thaicert.or.th/papers/general/2013/pa2013ge002.html" title="https://www.thaicert.or.th/papers/general/2013/pa2013ge002.html">https://www.thaicert.or.th/papers/general/2013/pa2013ge002.html</a></p>
<p>หลังจากที่ยืนยันอีเมลเสร็จแล้ว ให้ผู้อ่านเตรียมความพร้อมของไฟล์เหล่านี้</p>
<ol><li>ไฟล์ setup.py</li></ol>
<p>ต้องมีรายละเอียดดังนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">from</span> distutils.core <span class="hljs-keyword">import</span> setup
<span class="hljs-keyword">def</span> <span class="hljs-title function_">read</span>(<span class="hljs-params">*paths</span>):
<span class="hljs-string">"""สำหรับใช้ดึงข้อมูลจากไฟล์มาแสดง"""</span>
<span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(os.path.join(*paths), <span class="hljs-string">'r'</span>) <span class="hljs-keyword">as</span> f:
<span class="hljs-keyword">return</span> f.read()
setup(
name = <span class="hljs-string">'mypackage'</span>, <span class="hljs-comment"># ชื่อโมดูล</span>
packages = [<span class="hljs-string">'mypackage'</span>], <span class="hljs-comment"># โฟลเลอร์ไลบรารี</span>
version = <span class="hljs-string">'0.1'</span>, <span class="hljs-comment">#เวอร์ชั่นโมดูล</span>
description = <span class="hljs-string">'รายละเอียด'</span>,
long_description=(read(<span class="hljs-string">'README.txt'</span>)), <span class="hljs-comment">#รายละเอียดการใช้งานโมดูล</span>
author = <span class="hljs-string">''</span>, <span class="hljs-comment"># ชื่อนักพัฒนา</span>
author_email = <span class="hljs-string">''</span>, <span class="hljs-comment"># อีเมลนักพัฒนา</span>
url = <span class="hljs-string">''</span>, <span class="hljs-comment"># ลิงค์หน้าหลักโมดูล</span>
<span class="hljs-comment">#download_url = '', # ลิงค์ดาวน์โหลด</span>
keywords = [<span class="hljs-string">'testing'</span>, <span class="hljs-string">'logging'</span>, <span class="hljs-string">'example'</span>], <span class="hljs-comment"># คำค้น</span>
classifiers=[
<span class="hljs-string">'Development Status :: 5 - Production/Stable'</span>,
<span class="hljs-string">'Intended Audience :: Developers'</span>,
<span class="hljs-string">'Natural Language :: English'</span>,
<span class="hljs-string">'License :: OSI Approved :: MIT License'</span>,
<span class="hljs-string">'Operating System :: OS Independent'</span>,
<span class="hljs-string">'Programming Language :: Python'</span>,
<span class="hljs-string">'Programming Language :: Python :: 2'</span>,
<span class="hljs-string">'Programming Language :: Python :: 3'</span>,
<span class="hljs-string">'Topic :: Scientific/Engineering'</span>,] <span class="hljs-comment"># รายละเอียดเบื้องต้นของโมดูล</span>
],
)</code></pre>
</div>
<ol start="2"><li>
<p>ไฟล์โมดูล</p>
</li><li>
<p>ไฟล์ README.txt</p>
</li></ol>
<p>ไฟล์ README.txt นี้เป็นรายละเอียดการใช้งานโมดูลของเรา เหมือนที่เราเห็นทั่วไปตามหน้าเพจของ PyPI<br />สามารถสร้างไฟล์โดยอาคัยเครื่องมือจากเว็บ <a data-from-md="" href="http://rst.ninjs.org/" title="http://rst.ninjs.org/">http://rst.ninjs.org</a></p>
<ol start="4"><li>ไฟล์ LICENSE.txt เป็นไฟล์ที่ระบุลิขสิทธิ์การใช้งานโมดูลของเรา เช่น ผมเลือก MIT สามารถเข้าไปที่ <a data-from-md="" href="http://opensource.org/licenses/MIT" title="http://opensource.org/licenses/MIT">http://opensource.org/licenses/MIT</a></li></ol>
<p>เพื่อก็อบ LICENSE มาวางไว้ที่ LICENSE.txt ได้เลย</p>
<blockquote>
<p>แนะนำให้ใช้ภาษาอังกฤษทั้งหมด</p>
</blockquote>
<p>เปิดคอมมานด์ไลน์เข้าไปยังโฟลเลอร์ที่เก็บไฟล์ setup.py ของโมดูล แล้วใช้คำสั่ง</p>
<blockquote>
<p>python setup.py register</p>
</blockquote>
<div class="joplin-editable">
<pre class="hljs"><code>><span class="hljs-keyword">python</span> setup.<span class="hljs-keyword">py</span> register
running register
running check
We need <span class="hljs-keyword">to</span> know who you are, <span class="hljs-keyword">so</span> please choose either:
<span class="hljs-number">1</span>. use your existing login,
<span class="hljs-number">2</span>. register <span class="hljs-keyword">as</span> <span class="hljs-keyword">a</span> <span class="hljs-keyword">new</span> user,
<span class="hljs-number">3</span>. have the server generate <span class="hljs-keyword">a</span> <span class="hljs-keyword">new</span> password <span class="hljs-keyword">for</span> you (<span class="hljs-built_in">and</span> email it <span class="hljs-keyword">to</span> you), <span class="hljs-built_in">or</span>
<span class="hljs-number">4</span>. <span class="hljs-keyword">quit</span>
Your selection [default <span class="hljs-number">1</span>]:
<span class="hljs-number">1</span>
Username:
Password:
Registering pytemperature <span class="hljs-keyword">to</span> https://pypi.<span class="hljs-keyword">python</span>.org/pypi
Server response (<span class="hljs-number">200</span>): OK
I can store your PyPI login <span class="hljs-keyword">so</span> future submissions will <span class="hljs-keyword">be</span> faster.
(the login will <span class="hljs-keyword">be</span> stored in C:\Users\วรรณพงษ์\.pypirc)
Save your login (<span class="hljs-keyword">y</span>/<span class="hljs-keyword">N</span>)?<span class="hljs-keyword">y</span></code></pre>
</div>
<p>แล้วใช้คำสั่ง</p>
<blockquote>
<p>python setup.py sdist</p>
</blockquote>
<p>จะได้โฟลเลอร์ dist โดยข้างในจะเก็บไฟล์บีบอัดโมดูลไว้</p>
<p>เสร็จแล้วทำการติดตั้งโมดูล twine เป็นโมดูลที่ช่วยอัพโหลดไฟล์ขึ้น PyPI</p>
<blockquote>
<p>pip install twine</p>
</blockquote>
<p>จากนั้นทำการอัพโหลดไฟล์โมดูลขึ้น pypi</p>
<blockquote>
<p>twine upload dist/*</p>
</blockquote>
<p>หลังจากนี้สามารถติดตั้งโมดูลของคุณได้จากคำสั่ง</p>
<blockquote>
<p>pip install ชื่อโมดูลของคุณ</p>
</blockquote>
<h2 id="บทที่-21-เริ่มต้นกับ-numpy">บทที่ 21 เริ่มต้นกับ NumPy</h2>
<p>โมดูล NumPy เป็นโมดูลส่วนเสริมของภาษา Python สำหรับใช้คำนวณทางคณิตศาสตร์และวิทยาศาสตร์ โดยมีคำสั่งพร้อมใช้งานจำนวนมากมาย และโมดูลนี้สามารถสร้างข้อมูลชนิดอาร์เรย์ (ที่ภาษา Python ไม่มี) และคำนวณอาร์เรย์ของตัวเลข สตริงและวัตถุได้</p>
<p>โมดูล NumPy รองรับทั้ง Python 2 , Python 3 และใช้ License: BSD</p>
<p><b>การติดตั้งโมดูล NumPy</b></p>
<p>สามารถติดตั้งได้โดยใช้คำสั่ง pip: (ตรวจสอบการตั้งค่า c compiler กับ Python ให้เรียบร้อยก่อนติดตั้งครับ)</p>
<div class="joplin-editable">
<pre class="hljs"><code>$ pip install numpy</code></pre>
</div>
<p>สำหรับผู้ใช้ Windows สามารถโหลดไฟล์ .whl มาติดตั้งได้จาก <a data-from-md="" href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy" title="http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy">http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy</a></p>
<h3 id="การใช้งาน-numpy">การใช้งาน NumPy</h3>
<p>ในการใช้งานต้อง import NumPy เข้ามา</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np</code></pre>
</div>
<p><b>ข้อมูลชนิดอาร์เรย์กับ NumPy</b></p>
<p>อย่างที่เรารู้กัน ภาษา Python ไม่มีข้อมูลชนิดอาร์เรย์ สามารถใช้ list แทนได้ แต่หากใช้โมดูล NumPy เราจะสามารถใช้ข้อมูลชนิดอาร์เรย์ได้ดังนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>x = np.array([<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>])
<span class="hljs-meta">>>> </span>x
array([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])</code></pre>
</div>
<p>ต่อไปเราจะมาสร้าง array เก็บข้อมูลระหว่าง 0 - 10 กัน</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>x = np.arange(<span class="hljs-number">10</span>)
<span class="hljs-meta">>>> </span>x
array([<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>])</code></pre>
</div>
<p>เมื่อเรานำ x ที่เก็บข้อมูลอาร์เรย์ของตัวเลขไว้ มาบวกกับ 10 และนำมาบวกกับตัวมันเอง</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>x = np.arange(<span class="hljs-number">10</span>)
<span class="hljs-meta">>>> </span>x
array([<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>])
<span class="hljs-meta">>>> </span>y = x + <span class="hljs-number">10</span> <span class="hljs-comment"># มาบวกกับ 10</span>
<span class="hljs-meta">>>> </span>y
array([<span class="hljs-number">10</span>, <span class="hljs-number">11</span>, <span class="hljs-number">12</span>, <span class="hljs-number">13</span>, <span class="hljs-number">14</span>, <span class="hljs-number">15</span>, <span class="hljs-number">16</span>, <span class="hljs-number">17</span>, <span class="hljs-number">18</span>, <span class="hljs-number">19</span>])
<span class="hljs-meta">>>> </span>z = x + x <span class="hljs-comment"># บวกกับตัวมันเอง</span>
<span class="hljs-meta">>>> </span>z
array([ <span class="hljs-number">0</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>, <span class="hljs-number">10</span>, <span class="hljs-number">12</span>, <span class="hljs-number">14</span>, <span class="hljs-number">16</span>, <span class="hljs-number">18</span>])</code></pre>
</div>
<p>การเรียกใช้ข้อมูลจากอาร์เรย์ และแทนที่ข้อมูลในอาร์เรย์ได้ดังนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>x = np.arange(<span class="hljs-number">10</span>)
<span class="hljs-meta">>>> </span>x
array([<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>])
<span class="hljs-meta">>>> </span>x[<span class="hljs-number">1</span>]
<span class="hljs-number">1</span>
<span class="hljs-meta">>>> </span>x[<span class="hljs-number">8</span>]
<span class="hljs-number">8</span>
<span class="hljs-meta">>>> </span>x[<span class="hljs-number">9</span>]
<span class="hljs-number">9</span>
<span class="hljs-meta">>>> </span>x[<span class="hljs-number">0</span>] = <span class="hljs-number">99</span>
<span class="hljs-meta">>>> </span>x
array([<span class="hljs-number">99</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>])</code></pre>
</div>
<p>หาค่าสูงสุด ต่ำสุด</p>
<div class="joplin-editable">
<pre class="hljs"><code>x = np.arange(<span class="hljs-number">5</span>) + <span class="hljs-number">1</span>
x.mean() <span class="hljs-comment"># ค่าเฉลี่ยเลขคณิต คือ 3.0</span>
x.<span class="hljs-built_in">max</span>() <span class="hljs-comment"># ค่ามากสุดือ 5</span>
x.<span class="hljs-built_in">min</span>() <span class="hljs-comment"># ค่าน้อยสุดคือ 1</span>
x.std() <span class="hljs-comment"># คำนวณส่วนเบี่ยงเบนมาตรฐาน คือ 1.414</span></code></pre>
</div>
<p>ต่อไปเราจะย้ายข้อมูลอาร์เรย์จากแถวเดียว (อาร์เรย์ 1 มิติ) ไปเป็น 2 แถว (อาร์เรย์ 2 มิติ) ได้ โดยแถวและหลักต้องสมดุลกัน เป็นเมทริกซ์ สามารถใช้คำสั่ง reshape() ได้ดังนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>x = np.arange(<span class="hljs-number">10</span>)
<span class="hljs-meta">>>> </span>y = x.reshape(<span class="hljs-number">2</span>,<span class="hljs-number">5</span>) <span class="hljs-comment"># สร้างเมทริกซ์ 2 * 5</span>
<span class="hljs-meta">>>> </span>y
array([[<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>],
[<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>]])</code></pre>
</div>
<p>หากเรากำหนดค่าเมทริกซ์ไม่สมดุลกัน จะเกิดข้อผิดพลาดขึ้น เนื่องจากค่าเมทริกซ์ไม่สมดุล</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>x = np.arange(<span class="hljs-number">10</span>)
<span class="hljs-meta">>>> </span>y = x.reshape(<span class="hljs-number">2</span>,<span class="hljs-number">2</span>)
Traceback (most recent call last):
File <span class="hljs-string">"<stdin>"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> <module>
ValueError: total size of new array must be unchanged</code></pre>
</div>
<p><b>เมทริกซ์</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-meta">>>> </span>A = np.matrix(<span class="hljs-string">'1.0 2.0; 3.0 4.0'</span>)
<span class="hljs-meta">>>> </span>A
[[ <span class="hljs-number">1.</span> <span class="hljs-number">2.</span>]
[ <span class="hljs-number">3.</span> <span class="hljs-number">4.</span>]]
<span class="hljs-meta">>>> </span><span class="hljs-built_in">type</span>(A) <span class="hljs-comment"># ตรวจสอบชนิดของข้อมูลตัวแปร A</span>
<<span class="hljs-keyword">class</span> <span class="hljs-string">'numpy.matrixlib.defmatrix.matrix'</span>>
<span class="hljs-meta">>>> </span>A.T <span class="hljs-comment"># เมทริกซ์สลับเปลี่ยน (transpose)</span>
[[ <span class="hljs-number">1.</span> <span class="hljs-number">3.</span>]
[ <span class="hljs-number">2.</span> <span class="hljs-number">4.</span>]]
<span class="hljs-meta">>>> </span>X = np.matrix(<span class="hljs-string">'5.0 7.0'</span>)
<span class="hljs-meta">>>> </span>Y = X.T
<span class="hljs-meta">>>> </span>Y
[[<span class="hljs-number">5.</span>]
[<span class="hljs-number">7.</span>]]
<span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(A*Y) <span class="hljs-comment"># การคูณเมทริกซ์</span>
[[<span class="hljs-number">19.</span>]
[<span class="hljs-number">43.</span>]]
<span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(A.I) <span class="hljs-comment"># อินเวอร์สของเมทริกซ์</span>
[[-<span class="hljs-number">2.</span> <span class="hljs-number">1.</span> ]
[ <span class="hljs-number">1.5</span> -<span class="hljs-number">0.5</span>]]</code></pre>
</div>
<p>อ่านเอกสารการใช้งาน NumPy เพิ่มเติมได้ที่ <a data-from-md="" href="http://wiki.scipy.org/Tentative_NumPy_Tutorial" title="http://wiki.scipy.org/Tentative_NumPy_Tutorial">http://wiki.scipy.org/Tentative_NumPy_Tutorial</a></p>
<h2 id="บทที่-22-เชื่อมต่อฐานข้อมูล-mysql-ด้วยภาษาไพทอน">บทที่ 22 เชื่อมต่อฐานข้อมูล MySQL ด้วยภาษาไพทอน</h2>
<p>ในการเชื่อมต่อฐานข้อมูล MySQL ด้วยภาษาไพทอนสามารถใช้โมดูล mysql-connector ในการเชื่อมต่อฐานข้อมูล MySQLได้</p>
<p>โมดูล mysql-connector-python เป็น MySQL driver ที่เขียนในภาษาไพทอนทั้งหมด<br />(ไม่มีปัญหาเรื่องความเข้ากันได้) พร้อมรองรับ DB API v2.0 specification<br />(PEP-249) พัฒนาโดย Oracle</p>
<p>ใช้ License: GNU GPLv2</p>
<p>รองรับทั้ง Python 2 และ Python 3</p>
<p>สามารถติดตั้งได้โดยใช้คำสั่ง pip :</p>
<div class="joplin-editable">
<pre class="hljs"><code>pip <span class="hljs-keyword">install</span> mysql-connector-python</code></pre>
</div>
<h3 id="เอกสารการใช้งาน">เอกสารการใช้งาน</h3>
<p>ในการเรียกใช้งานโมดูลนี้ต้อง</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> mysql.connector</code></pre>
</div>
<p>เข้ามาทุกครั้ง</p>
<p><b>การเชื่อมต่อกับฐานข้อมูล</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> mysql.connector
<span class="hljs-comment"># user: scott</span>
<span class="hljs-comment"># password: tiger</span>
<span class="hljs-comment"># host: 127.0.0.1</span>
<span class="hljs-comment"># database: employees</span>
cnx = mysql.connector.connect(user=<span class="hljs-string">'scott'</span>, password=<span class="hljs-string">'tiger'</span>,host=<span class="hljs-string">'127.0.0.1'</span>,database=<span class="hljs-string">'employees'</span>)
cnx.close()</code></pre>
</div>
<p>หากต้องการจัดการข้อผิดพลาดสามารถใช้ try except เข้ามาช่วยได้ดังนี้</p>
<p>แต่หากไม่ต้องการกรอกข้อมูลลงใน argument สามารถใช้ข้อมูลชนิด dictionary ช่วยในการเชื่อมต่อกับ</p>
<p>ฐานข้อมูลได้ดังนี้</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> mysql.connector
config = {
<span class="hljs-string">'user'</span>: <span class="hljs-string">'scott'</span>,
<span class="hljs-string">'password'</span>: <span class="hljs-string">'tiger'</span>,
<span class="hljs-string">'host'</span>: <span class="hljs-string">'127.0.0.1'</span>,
<span class="hljs-string">'database'</span>: <span class="hljs-string">'employees'</span>,
<span class="hljs-string">'raise_on_warnings'</span>: <span class="hljs-literal">True</span>,
}
cnx = mysql.connector.connect(**config)
cnx.close()</code></pre>
</div>
<h3 id="การใช้คําสั่ง-sql-กับฐานข้อมูล-mysql-ในภาษาไพทอน">การใช้คำสั่ง SQL กับฐานข้อมูล MySQL ในภาษาไพทอน</h3>
<p>เราสามารถใช้คำสั่ง SQL เพื่อสร้างฐานข้อมูล สร้างตาราง เพิ่มข้อมูลลงตาราง ปรับเปลี่ยนข้อมูล และลบข้อมูลได้ โดยใช้คำสั่ง</p>
<blockquote>
<p>cursor.execute(โค้ด SQl)</p>
</blockquote>
<p>เมื่อใช้งานคำสั่งเสร็จ ต้องใช้คำสั่ง</p>
<blockquote>
<p>commit()</p>
</blockquote>
<p>เพื่อบันทึกข้อมูลเสมอ</p>
<p><b>ตัวอย่างเช่น</b></p>
<p>ใช้คำสั่งสร้างตาราง</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> mysql.connector
<span class="hljs-keyword">from</span> mysql.connector <span class="hljs-keyword">import</span> errorcode
con = mysql.connector.connect(user=<span class="hljs-string">'scott'</span>, password=<span class="hljs-string">'tiger'</span>,host=<span class="hljs-string">'127.0.0.1'</span>,database=<span class="hljs-string">'employees'</span>)cursor = con.cursor()
sql = <span class="hljs-string">'''CREATE TABLE foo (
bar VARCHAR(50) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1
'''</span>
cursor.execute(sql)
con.commit()
con.close()</code></pre>
</div>
<p><b>การเพิ่มข้อมูล</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> mysql.connector
con = mysql.connector.connect(user=<span class="hljs-string">'scott'</span>, password=<span class="hljs-string">'tiger'</span>,host=<span class="hljs-string">'127.0.0.1'</span>, database=<span class="hljs-string">'employees'</span>)
add_db = <span class="hljs-string">"insert into foo(bar) values('Tontan')"</span>
cursor = con.cursor()
ccursor.execute(add_db)
con.commit()
con.close()</code></pre>
</div>
<h3 id="การดึงข้อมูลมาใช้งาน">การดึงข้อมูลมาใช้งาน</h3>
<p>สามารถใช้คำสั่ง</p>
<blockquote>
<p>cursor.fetchall()</p>
</blockquote>
<p>หลังคำสั่ง</p>
<blockquote>
<p>cursor.execute(โค้ด SQl)</p>
</blockquote>
<p>โดยโค้ด SQl ต้องเป็นคำสั่ง query ข้อมูลตามหลักภาษา SQL</p>
<p><b>ตัวอย่าง</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> mysql.connector
con = mysql.connector.connect(user=<span class="hljs-string">'scott'</span>, password=<span class="hljs-string">'tiger'</span>,host=<span class="hljs-string">'127.0.0.1'</span>,database=<span class="hljs-string">'employees'</span>)
cursor = con.cursor()
sql = (<span class="hljs-string">"select bar from foo"</span>)
cursor.execute(sql)
data = cursor.fetchall() <span class="hljs-comment"># ได้ผลลัพธ์ออกมาในรูป list</span>
<span class="hljs-built_in">print</span>(data[<span class="hljs-number">0</span>])</code></pre>
</div>
<p>ผลลัพธ์</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-attribute">Tontan</span></code></pre>
</div>
<p>เอกสารการใช้งาน <a data-from-md="" href="http://dev.mysql.com/doc/connector-python/en/" title="http://dev.mysql.com/doc/connector-python/en/">http://dev.mysql.com/doc/connector-python/en/</a></p>
<h2 id="บทที่-23-เชื่อมต่อกับฐานข้อมูล-sqlite-ใน-python-3">บทที่ 23 เชื่อมต่อกับฐานข้อมูล SQLite ใน Python 3</h2>
<p>การเรียกใช้ฐานข้อมูล SQLite ใน Python 3 เราต้องเรียกใช้โมดูลมาตรฐาน sqlite3 ด้วยการ import เข้ามา</p>
<blockquote>
<p>import sqlite3</p>
</blockquote>
<p>ในการเชื่อมต่อฐานข้อมูลเราจะใช้คำสั่ง</p>
<blockquote>
<p>sqlite3.connect(database [,timeout ,other optional arguments])</p>
</blockquote>
<p>หากต้องการ cursor ฐานข้อมูลใช้คำสั่ง</p>
<blockquote>
<p>connection.cursor([cursorClass])</p>
</blockquote>
<p>รันคำสั่ง SQL กับฐานข้อมูล SQLite ใช้คำสั่ง</p>
<blockquote>
<p>cursor.execute(คำสั่ง sql [, optional parameters])</p>
</blockquote>
<p>fetchall ใช้คำสั่ง</p>
<blockquote>
<p>cursor.fetchall()</p>
</blockquote>
<p>หลังเพิ่มลบแก้ไข ให้</p>
<blockquote>
<p>connection.commit()</p>
</blockquote>
<p>ปิดการเชื่อมต่อกับฐานข้อมูล SQLite</p>
<blockquote>
<p>connection.close()</p>
</blockquote>
<p>เรามาเริ่มลองเขียนโปรแกรมกันครับ</p>
<h3 id="เปิดฐานข้อมูล-sqlite-ใน-python-3">เปิดฐานข้อมูล SQLite ใน Python 3</h3>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-comment">#!/usr/bin/python</span>
<span class="hljs-keyword">import</span> sqlite3
conn = sqlite3.connect(<span class="hljs-string">'1.db'</span>) <span class="hljs-comment"># สร้างไฟล์ 1.db เป็นไฟล์ฐานข้อมูล</span>
<span class="hljs-built_in">print</span>(<span class="hljs-string">"เปิดฐานข้อมูลสำเร็จ"</span>)</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<p>เปิดฐานข้อมูลสำเร็จ</p>
</blockquote>
<p>และจะได้ไฟล์ฐานข้อมูล 1.db</p>
<h3 id="สร้างตารางฐานข้อมูล-sqlite-ใน-python-3">สร้างตารางฐานข้อมูล SQLite ใน Python 3</h3>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-comment">#!/usr/bin/python</span>
<span class="hljs-keyword">import</span> sqlite3
conn = sqlite3.connect(<span class="hljs-string">'1.db'</span>)
<span class="hljs-built_in">print</span>(<span class="hljs-string">"เปิดฐานข้อมูลสำเร็จ"</span>)
conn.execute(<span class="hljs-string">'''CREATE TABLE SAVEONE
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
MESSENGE CHAR(150));'''</span>)
<span class="hljs-built_in">print</span>(<span class="hljs-string">"สร้างตารางสำเร็จ :D "</span>)
conn.close()</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<p>เปิดฐานข้อมูลสำเร็จ</p>
</blockquote>
<h3 id="เพิ่มข้อมูล-insert-ลงไปฐานข้อมูล-sqlite-ใน-python-3">เพิ่มข้อมูล INSERT ลงไปฐานข้อมูล SQLite ใน Python 3</h3>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-comment">#!/usr/bin/python</span>
<span class="hljs-keyword">import</span> sqlite3
conn = sqlite3.connect(<span class="hljs-string">'1.db'</span>)
<span class="hljs-built_in">print</span>(<span class="hljs-string">"เปิดฐานข้อมูลสำเร็จ"</span>)
conn.execute(<span class="hljs-string">"INSERT INTO SAVEONE (ID,NAME,MESSENGE ) \
VALUES (1, 'ต้นตาล','ทดสอบระบบ :D ')"</span>)
conn.execute(<span class="hljs-string">"INSERT INTO SAVEONE (ID,NAME,MESSENGE ) \
VALUES (2, 'วรรณพงษ์','ทดสอบระบบ ครับ :D ')"</span>)
conn.commit()
<span class="hljs-built_in">print</span>(<span class="hljs-string">"เพิ่มระเบียงข้อมูลสำเร็จ"</span>)
conn.close()</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<p>เปิดฐานข้อมูลสำเร็จ</p>
</blockquote>
<h3 id="อ่านข้อมูลด้วยการเลือกตาราง-select-กับฐานข้อมูล-sqlite-ใน-python-3">อ่านข้อมูลด้วยการเลือกตาราง (SELECT) กับฐานข้อมูล SQLite ใน Python 3</h3>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-comment">#!/usr/bin/python</span>
<span class="hljs-keyword">import</span> sqlite3
conn = sqlite3.connect(<span class="hljs-string">'1.db'</span>)
<span class="hljs-built_in">print</span>(<span class="hljs-string">"เปิดฐานข้อมูลสำเร็จ"</span>)
cursor = conn.execute(<span class="hljs-string">"SELECT ID,NAME,MESSENGE from SAVEONE"</span>)
<span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> cursor:
<span class="hljs-built_in">print</span>(<span class="hljs-string">"ID = "</span>, row[<span class="hljs-number">0</span>])
<span class="hljs-built_in">print</span>(<span class="hljs-string">"NAME = "</span>, row[<span class="hljs-number">1</span>])
<span class="hljs-built_in">print</span>(<span class="hljs-string">"MESSENGE = "</span>, row[<span class="hljs-number">2</span>])
<span class="hljs-built_in">print</span>(<span class="hljs-string">"ดำเนินการเสร็จสิ้น"</span>)
conn.close()
</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<p>เปิดฐานข้อมูลสำเร็จ</p>
</blockquote>
<h3 id="fetchall-ฐานข้อมูล">fetchall ฐานข้อมูล</h3>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> sqlite3
<span class="hljs-keyword">import</span> sys
conn = sqlite3.connect(<span class="hljs-string">'1.db'</span>)
<span class="hljs-keyword">with</span> conn:
cur = conn.cursor()
cur.execute(<span class="hljs-string">"SELECT * FROM SAVEONE"</span>)
rows = cur.fetchall()
<span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> rows:
<span class="hljs-built_in">print</span>(row)
<span class="hljs-built_in">input</span>()</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<p>(1, 'ต้นตาล','ทดสอบระบบ 😄 ')</p>
</blockquote>
<h3 id="อัปเดรตข้อมูลใหม่โดยใช้คําสั่ง-update-กับฐานข้อมูล-sqlite-ใน-python-3"><b>อัปเดรตข้อมูลใหม่โดยใช้คำสั่ง UPDATE กับฐานข้อมูล SQLite ใน Python 3</b></h3>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-comment">#!/usr/bin/python</span>
<span class="hljs-keyword">import</span> sqlite3
conn = sqlite3.connect(<span class="hljs-string">'1.db'</span>)
<span class="hljs-built_in">print</span>(<span class="hljs-string">"เปิดฐานข้อมูลสำเร็จ"</span>)
conn.execute(<span class="hljs-string">"UPDATE SAVEONE set NAME = 'HI' where ID=1"</span>)
conn.commit()
<span class="hljs-built_in">print</span>(<span class="hljs-string">"แถวที่อัปเดรตข้อมูลใหม่ :"</span>, conn.total_changes)
cursor = conn.execute(<span class="hljs-string">"SELECT ID,NAME,MESSENGE from SAVEONE"</span>)
<span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> cursor:
<span class="hljs-built_in">print</span>(<span class="hljs-string">"ID = "</span>, row[<span class="hljs-number">0</span>])
<span class="hljs-built_in">print</span>(<span class="hljs-string">"NAME = "</span>, row[<span class="hljs-number">1</span>])
<span class="hljs-built_in">print</span>(<span class="hljs-string">"MESSENGE = "</span>, row[<span class="hljs-number">2</span>])
<span class="hljs-built_in">print</span>(<span class="hljs-string">"ดำเนินการเสร็จสิ้น"</span>)
conn.close()
<span class="hljs-built_in">input</span>()</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<p>เปิดฐานข้อมูลสำเร็จ</p>
</blockquote>
<h3 id="ลบข้อมูล-delete-กับฐานข้อมูล-sqlite-ใน-python-3">ลบข้อมูล (DELETE) กับฐานข้อมูล SQLite ใน Python 3</h3>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-comment">#!/usr/bin/python</span>
<span class="hljs-keyword">import</span> sqlite3
conn = sqlite3.connect(<span class="hljs-string">'1.db'</span>)
<span class="hljs-built_in">print</span>(<span class="hljs-string">"เปิดฐานข้อมูลสำเร็จ"</span>)
conn.execute(<span class="hljs-string">"DELETE from SAVEONE where ID=2;"</span>)
conn.commit()
<span class="hljs-built_in">print</span>(<span class="hljs-string">"แถวที่ถูกลบ :"</span>, conn.total_changes)
cursor = conn.execute(<span class="hljs-string">"SELECT ID,NAME,MESSENGE from SAVEONE"</span>)
<span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> cursor:
<span class="hljs-built_in">print</span>(<span class="hljs-string">"ID = "</span>, row[<span class="hljs-number">0</span>])
<span class="hljs-built_in">print</span>(<span class="hljs-string">"NAME = "</span>, row[<span class="hljs-number">1</span>])
<span class="hljs-built_in">print</span>(<span class="hljs-string">"MESSENGE = "</span>, row[<span class="hljs-number">2</span>])
<span class="hljs-built_in">print</span>(<span class="hljs-string">"ดำเนินการเสร็จสิ้น"</span>)
conn.close()
<span class="hljs-built_in">input</span>()</code></pre>
</div>
<p><b>ผลลัพธ์</b></p>
<blockquote>
<p>เปิดฐานข้อมูลสำเร็จ</p>
</blockquote>
<p>อ่านรายละเอียดเพิ่มเติมได้ที่ <a data-from-md="" href="https://docs.python.org/3/library/sqlite3.html" title="https://docs.python.org/3/library/sqlite3.html">https://docs.python.org/3/library/sqlite3.html</a></p>
<h2 id="บทที่-23-เขียนโปรแกรมเครือข่าย-socket-ใน-python">บทที่ 23 เขียนโปรแกรมเครือข่าย Socket ใน Python</h2>
<p>Socket ในความหมายภาษาไทยแบบง่าย ๆ หมายถึง<br />เต้ารับที่สามาเอาอุปกรณ์มาเชื่อมต่อกันได้ เหมือนเต้ารับของปลั๊กไฟ<br />ในการเขียนโปรแกรม Socket คือ การสื่อสารระหว่างโปรแกรมบนเครือข่าย<br />ในการเขียนโปรแกรมเชื่อมต่อการสื่อสารนั้นเราต้องใช้ Socket API<br />โดยต้องระบุถึงโปรแกรมผ่าน Port Number<br />และที่อยู่ของเครื่องอีกเครื่องหนึ่งบนเครือข่ายด้วย IP Address</p>
<p><b>สรุป</b></p>
<blockquote>
<p>Socket Address = IP Address + Port Number</p>
</blockquote>
<p>ในการเขียนโปรแกรมในปัจจุบัน ภาษาคอมพิวเตอร์ต่าง ๆ ได้รองรับ Socket<br />กันไปนานแล้ว เช่น Java , Python , C/C++ เป็นต้น การใช้งาน Socket<br />จึงไม่ได้จำกัดแค่ภาษาใดภาษาหนึ่ง</p>
<p>ในการเขียนโปรแกรมภาษา Python ได้รวม Socket API เข้ามาตั้งแต่ต้นแล้ว เวลาเรียกใช้งานต้อง</p>
<blockquote>
<p>import socket</p>
</blockquote>
<p>เข้ามาในโค้ดโปรแกรม</p>
<p><b>รายละเอียดเบื้องต้นของโมดูล Socket ใน Python :</b></p>
<ul><li>socket.listen() – listen สำหรับการเชื่อมต่อขาเข้า</li><li>socket.accept() – ยอมรับการเชื่อมต่อขาเข้า</li><li>socket.recv() – ส่งกลับข้อมูลที่เข้ามาเป็น string</li><li>socket.send() – ส่งข้อมูลไปยังไคลเอนต์ socket</li><li>socket.close() – ปิดซ็อกเก็ต</li></ul>
<p>มาลองเขียนโปรแกรมเครือข่าย Socket ส่งข้อมูลข้ามเครือข่ายกัน</p>
<p>ในการรับส่งข้อมูล ต้องมีผู้ส่งสาร สื่อ และผู้รับสาร โดยส่ง และรับข้อมูล โดย TCP ใน Python</p>
<p><b>โค้ด client.py</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> socket
TCP_IP = <span class="hljs-string">"127.0.0.1"</span> <span class="hljs-comment"># ที่อยู่ ip</span>
TCP_PORT = <span class="hljs-number">8081</span> <span class="hljs-comment"># port</span>
BUFFER_SIZE = <span class="hljs-number">1024</span>
MESSAGE = <span class="hljs-string">"Hello, World!"</span> <span class="hljs-comment"># ข้อความที่จะส่ง</span>
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP,TCP_PORT)) <span class="hljs-comment">#เชื่อมต่อ</span>
s.send(MESSAGE.encode(<span class="hljs-string">'utf-8'</span>)) <span class="hljs-comment">#ส่งข้อมูลโดยก่อนส่งได้เข้ารหัสตัวอักษรเป็น utf-8</span>
data = s.recv(BUFFER_SIZE) <span class="hljs-comment">#ดึงผลลัพธ์การส่งข้อมูล</span>
s.close() <span class="hljs-comment">#จบการเชื่อมต่อ</span>
<span class="hljs-built_in">print</span>(<span class="hljs-string">"received data:"</span>, data) <span class="hljs-comment">#แสดงผลลัพธ์การส่งข้อมูล</span></code></pre>
</div>
<p><b>โค้ด server.py</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> socket
TCP_IP = <span class="hljs-string">"127.0.0.1"</span>
TCP_PORT = <span class="hljs-number">8081</span>
BUFFER_SIZE = <span class="hljs-number">1024</span>
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP,TCP_PORT)) <span class="hljs-comment">#เชื่อมต่อ</span>
s.listen(<span class="hljs-number">1</span>)
conn, addr = s.accept() <span class="hljs-comment">#รอรับข้อมูลที่ส่งมาจาก client.py</span>
<span class="hljs-built_in">print</span>(<span class="hljs-string">'Connection address:'</span>, addr) <span class="hljs-comment">#แสดงลายละเอียดของ client ที่เชื่อมต่อมา</span>
<span class="hljs-keyword">while</span> <span class="hljs-number">1</span>:
data = conn.recv(BUFFER_SIZE)
<span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> data: <span class="hljs-keyword">break</span>
<span class="hljs-built_in">print</span>(<span class="hljs-string">"received data:"</span>, data) <span class="hljs-comment">#แสดงข้อมูลที่ส่งมา</span>
conn.send(data) <span class="hljs-comment"># echo</span>
conn.close() <span class="hljs-comment">#จบการเชื่อมต่อ</span></code></pre>
</div>
<p>ในการรัน ต้องรันไฟล์ server.py ก่อนครับ เพราะ server.py เป็นไฟล์เซิร์ฟเวอร์สำหรับรับและส่งข้อมูล แล้วจึงค่อยรัน client.py</p>
<p><b>ผลลัพธ์</b></p>
<p>ไฟล์ server.py</p>
<div class="joplin-editable">
<pre class="hljs"><code>Connection <span class="hljs-selector-tag">address</span>: (<span class="hljs-string">'127.0.0.1'</span>, <span class="hljs-number">60447</span>)
received data: b<span class="hljs-string">'Hello, World!'</span></code></pre>
</div>
<p>ไฟล์ client.py</p>
<blockquote>
<p>received data: b'Hello, World!'</p>
</blockquote>
<p>จากโปรแกรมข้างบนจะพบว่า เราได้กำหนดค่า IP Address เป็น 127.0.0.1<br />นั้นคือส่งข้อมูลภายในเครื่อง เพื่อทดสอบโปรแกรมและกำหนดค่า Port Number<br />เป็น 8081 โดย Port Number ต้องห้ามซ้ำกับ Port Number ที่มีอยู่ในระบบ<br />หากเอาไปใช้งานผ่านเครือข่ายให้แก้ IP Address และ Port Number<br />ตามที่ต้องการ</p>
<h2 id="python-cheat-sheet-เบื้องต้น">Python Cheat Sheet เบื้องต้น</h2>
<p>เป็น Cheat Sheet สำหรับไวยากรณ์ภาษา Python เบื้องต้น</p>
<h3 id="การดําเนินการทางตรรกะพื้นฐาน"><b>การดำเนินการทางตรรกะพื้นฐาน</b></h3>
<p>if :</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">if</span> test:
หาก test เป็นจริงจะทำงานตามคำสั่งในนี้
<span class="hljs-keyword">elif</span> test2:
หาก test2 เป็นจริงจะทำงานตามคำสั่งในนี้
<span class="hljs-keyword">else</span>:
หากเงื่อนไขทั้งหมดเป็นเท็จ จะทำงานตามนี้
</code></pre>
</div>
<h3 id="python-loop"><b>Python loop</b></h3>
<p>for :</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> aSequence:
<span class="hljs-comment">#ดำเนินการสมาชิกแต่ละตัวใน aSequence</span>
<span class="hljs-comment">#ตัวอย่างเช่น สมาชิกที่อยู่ใน list</span>
<span class="hljs-comment">#ตัวอักษรที่อยู่ใน string เป็นต้น</span>
<span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">10</span>):
<span class="hljs-comment">#ดำเนินการ 10 ครั้ง (0 ถึง 9)</span>
<span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">5</span>,<span class="hljs-number">10</span>):
<span class="hljs-comment">#ดำเนินการ 5 ครั้ง (5 ถึง 9)</span></code></pre>
</div>
<p>while :</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">while</span> test:
<span class="hljs-comment">#ทำจนกว่าจะสิ้นสุด</span>
<span class="hljs-comment">#จนกว่า test จะเป็น false</span></code></pre>
</div>
<h3 id="python-strings"><b>Python Strings</b></h3>
<p>Strings เป็นลำดับของอักษระที่เรียงต่อกัน มักเป็นข้อความที่เก็บไว้<br />การสร้าง :</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-attr">the_string</span> = <span class="hljs-string">"Hello World!"</span>
<span class="hljs-attr">the_string</span> = <span class="hljs-string">'Hello World!'</span>
</code></pre>
</div>
<p>การเข้าถึงตัวอักษรตามลำดับ <code class="inline-code" spellcheck="false">the_string[1]</code> คืนค่า <code class="inline-code" spellcheck="false">e</code><br />การแยก String <code class="inline-code" spellcheck="false">the_string.split(" ")</code> คืนค่า <code class="inline-code" spellcheck="false">['Hello', 'World!']</code></p>
<p>ในการแปลง List เป็นสตริง เราสามารถทำได้ด้วยคำสั่ง join()</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-attr">words</span> = [<span class="hljs-string">"this"</span>, <span class="hljs-string">"is"</span>, <span class="hljs-string">"a"</span>, <span class="hljs-string">"list"</span>, <span class="hljs-string">"of"</span>, <span class="hljs-string">"strings"</span>]
</code></pre>
</div>
<p><code class="inline-code" spellcheck="false">' '.join(words)</code> คืนค่า <code class="inline-code" spellcheck="false">"This is a list of strings"</code><br /><code class="inline-code" spellcheck="false">'ZOOL'.join(words)</code> คืนค่า <code class="inline-code" spellcheck="false">"ThisZOOLisZOOLaZOOLlistZOOLofZOOLstrings"</code><br /><code class="inline-code" spellcheck="false">"".join(words)</code> คืนค่า <code class="inline-code" spellcheck="false">"Thisisalistofstrings"</code></p>
<p>String Formatting : เหมือนกับ printf() ของภาษา C โดยใช้ % หลังสตริงตามด้วย tuple โดยมีสตริงอยู่ภายใน เช่น</p>
<div class="joplin-editable">
<pre class="hljs"><code>the_string = <span class="hljs-string">"Hello World!"</span>
<span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(<span class="hljs-string">"text : %s"</span> % the_string)</span></span>
</code></pre>
</div>
<p>ผลลัพธ์ text : Hello World!</p>
<p>แปลงสตริงจากตัวพิมพ์ใหญ่เป็นตัวพิมพ์เล็ก "PYTHON".lower() คืนค่า "python"<br />แปลงสตริงจากตัวพิมพ์เล็กเป็นตัวพิมพ์ใหญ่ "python".upper() คืนค่า PYTHON<br />นับจำนวนสตริงที่กำหนด "pythonpy".count("py") คืนค่า 2<br />ค้นหาตำแหน่งสตริงที่ต้องการ "python".find("n") คืนค่า 5 และสามารถค้นหาแบบกำหนดช่วงได้ "pythonpython".find("n",4,6) คืนค่า 5<br />แทนที่สตริง "pythonpython".replace("py","go") คืนค่า "gothongothon"</p>
<h3 id="python-dictionaries">Python Dictionaries</h3>
<p>การสร้าง :</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-attr">emptyDict</span> = {}
<span class="hljs-attr">thisdict</span> = {<span class="hljs-string">"a"</span>:<span class="hljs-number">1</span>, <span class="hljs-string">"b"</span>:<span class="hljs-number">23</span>, <span class="hljs-string">"c"</span>:<span class="hljs-string">"eggs"</span>}
</code></pre>
</div>
<p>การดึงข้อมูล : thisdict["a"] คืนค่า 1</p>
<h3 id="python-list">Python List</h3>
<p>การสร้าง List :</p>
<div class="joplin-editable">
<pre class="hljs"><code>thelist = [<span class="hljs-string">'5'</span>, <span class="hljs-string">'3'</span>, <span class="hljs-string">'p'</span>, <span class="hljs-string">'9'</span>, <span class="hljs-string">'e'</span>]
thelist = list(<span class="hljs-string">'53p9e'</span>) # [<span class="hljs-string">'5'</span>, <span class="hljs-string">'3'</span>, <span class="hljs-string">'p'</span>, <span class="hljs-string">'9'</span>, <span class="hljs-string">'e'</span>]
</code></pre>
</div>
<p>การเข้าถึงข้อมูล : thelist[0] คืนค่า '5'<br /><b>ดึง List เฉพาะส่วนที่ต้องการ :</b><br />thelist[1:3] คืนค่า ['3', 'p']<br />thelist[2:] คืนค่า ['p', '9', 'e']<br />thelist[:2] คืนค่า ['5', '3']<br />thelist[2:-1] คืนค่า ['p', '9']<br />วัดความยาว len(thelist) คืนค่า 5<br />เรียงลำดับ list ใหม่ thelist.sort() ตอนนี้ list กลายเป็น [3,5,9,'e','p']<br />เพิ่ม thelist.append(7) ตอนนี้ list กลายเป็น [3,5,9,'e','p',7]<br />คืนค่า และ ลบค่าออก thelist.pop() คืนค่า 7 ตอนนี้ list กลายเป็น [3,5,9,'e','p']<br />แทรก List thelist.insert(1, 't') ตอนนี้ list กลายเป็น ['5', 't', '3', 'p', '9', 'e']<br />ลบค่า thelist.remove("t") ตอนนี้ list กลายเป็น ['5', '3', 'p', '9', 'e']<br />del thelist[0] ตอนนี้ list กลายเป็น ['3', 'p', '9', 'e']<br />บวก list thelist + [0] คืนค่า ['3', 'p', '9', 'e', 0]<br />ค้นหาค่าใน List '3' in thelist คืนค่า True</p>
<h3 id="python-tuples">Python Tuples</h3>
<p>การสร้าง Tuples :</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-attr">emptyTuple</span> = ()
<span class="hljs-attr">singleItemTuple</span> = (<span class="hljs-string">"spam"</span>,) <span class="hljs-comment"># note the comma!</span>
<span class="hljs-attr">thistuple</span> = <span class="hljs-number">12</span>, <span class="hljs-number">89</span>, <span class="hljs-string">'a'</span>
<span class="hljs-attr">thistuple</span> = (<span class="hljs-number">12</span>, <span class="hljs-number">89</span>, <span class="hljs-string">'a'</span>)
</code></pre>
</div>
<p>การดึงข้อมูล : thistuple[0] คืนค่า 12</p>
<h3 id="python-file">Python File</h3>
<p><b>การเปิดไฟล์:</b></p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-attr">thisfile</span> = open(<span class="hljs-string">"datadirectory/file.txt"</span>,โหมดเปิดไฟล์)</code></pre>
</div>
<p>โหมดการเปิดไฟล์</p>
<ul><li>w เขียนไฟล์</li><li>r อ่านไฟล์</li><li>a เขียนไฟล์ต่อจากข้อมูลเดิม</li></ul>
<p>หากไม่กำหนดโหมดการเปิดไฟล์ ค่าพื้นฐานเป็น r อ่านได้เท่านั้น</p>
<p><b>คำสั่งเพิ่มเติม</b></p>
<ul><li><code class="inline-code" spellcheck="false">thisfile.read()</code> อ่านสตริงตัวแรกจากไฟล์</li><li><code class="inline-code" spellcheck="false">thisfile.readline()</code> อ่านข้อมูล 1 บรรทัดจากไฟล์</li><li><code class="inline-code" spellcheck="false">thisfile.readlines()</code> อ่านข้อมูลจากบรรทัดทั้งหมดในไฟล์</li><li><code class="inline-code" spellcheck="false">for eachline in thisfile:</code> อ่านบรรทัดต่อบรรทัดในไฟล์</li><li><code class="inline-code" spellcheck="false">thisfile.write()</code> เขียนไฟล์</li><li><code class="inline-code" spellcheck="false">thisfile.close()</code> ปิดไฟล์</li></ul>
<p>หากทำงานกับภาษาไทย แนะนำให้ใช้ codecs โดยใช้ utf-8</p>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">import</span> codecs
thisfile = codecs.<span class="hljs-built_in">open</span>(<span class="hljs-string">"datadirectory/file.txt"</span>,โหมดเปิดไฟล์, encoding=<span class="hljs-string">"utf-8"</span>)</code></pre>
</div>
<h3 id="python-functions">Python Functions</h3>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">def</span> <span class="hljs-title function_">myFunc</span>(<span class="hljs-params">param1, param2</span>):
<span class="hljs-comment"># param1 และ param2 ใช้รับข้อมูลเมื่อใช้งาน myFunc(ข้อมูล1,ข้อมูล2)</span>
<span class="hljs-comment"># หากไม่มีการรับข้อมูล ไม่ต้องใส่ param ก็ได้</span>
<span class="hljs-keyword">return</span> param1+param2</code></pre>
</div>
<h3 id="python-class">Python Class</h3>
<div class="joplin-editable">
<pre class="hljs"><code><span class="hljs-keyword">class</span> <span class="hljs-title class_">FC</span>:
<span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self,one,ten</span>):
self.one = one
self.ten = ten
<span class="hljs-keyword">def</span> <span class="hljs-title function_">show</span>(<span class="hljs-params">self</span>):
<span class="hljs-built_in">print</span> (self.ten,<span class="hljs-string">"-"</span>,self.one,<span class="hljs-string">"="</span>,self.ten - self.one)
a = FC(one=<span class="hljs-number">1</span>,ten=<span class="hljs-number">10</span>)
a.show()</code></pre>
</div>
</div>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-48568561101242066972023-12-10T00:51:00.008+07:002023-12-10T00:51:48.542+07:00วิธีติดตั้ง python แบบง่าย ๆ ฉบับสั้น ๆ ประจำปี 2023<p>คุณสามารถติดตั้ง python ได้หลากหลายวิธีดังนี้<br />1) โหลด python จาก <a href="http://python.org" rel="nofollow" target="_blank">python.org</a> เป็นช่องทางอย่างเป็นทางการสำหรับ python คุณสามารถโหลดโปรแกรมและติดตั้งได้จากในนั้น</p><p>2) ใช้ Anaconda ซึ่งเป็นชุดรวมซอฟต์แวร์ python ที่เป็นนิยม คุณสามารถโหลด Anaconda แล้วติดตั้งได้จาก <a href="http://anaconda.org" rel="nofollow" target="_blank">anaconda.org</a> <br /></p>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-81870933677194774002022-07-31T19:26:00.004+07:002022-07-31T19:26:20.589+07:00PyPy สนับสนุนชิป Apple M1 แล้ว!<p></p><div class="separator" style="clear: both; text-align: center;"><img border="0" data-original-height="110" data-original-width="318" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgbIagTV4rZ8kWy_iT4pUCDH3DQh24oEBJigxA1501VT-SEpP5iHk2xDHV-CJxMRObjfYaBiHWEunQbeBwI0zG_bZjGPi4aG9-Cwo3lbTEknRWqmS4nsfQJKJTDDX0UMWSaRpMhrACb_lLgu349ZXR6MJKCrpY1udkr9Gta7b1vxvMKiKjG6VfnZfCt/s16000/pypy-logo.png" title="PyPy สนับสนุนชิป Apple M1 แล้ว!" /></div><p></p><p>เมื่อวันที่ 21 กรกฎาคมที่ผ่านมาทาง PyPy ได้ออกมาประกาศรองรับการทำงานบนชิป Apple M1 เป็นที่เรียบร้อยแล้ว บน macOS ARM64 โดยตอนนี้รุ่นสำหรับทดสอบ nightly builds รองรับ <a class="reference external" href="https://buildbot.pypy.org/nightly/py3.8/" rel="nofollow" target="_blank">pypy3.8</a> และ <a class="reference external" href="https://buildbot.pypy.org/nightly/py3.9/" rel="nofollow" target="_blank">pypy3.9</a> โดยเลือกดูรุ่ macOS ARM64 ได้</p><p>ที่มา: <a href="https://www.pypy.org/posts/2022/07/m1-support-for-pypy.html" rel="nofollow" target="_blank">M1 support for PyPy | PyPy</a><br /></p>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-77368292179873626122022-07-01T01:09:00.005+07:002022-07-01T01:10:32.987+07:00ปรับจูน Python ให้แรงขึ้นง่าย ๆ ด้วย Pyston-lite<p>เมื่อต้นเดือนมิถุนายนที่ผ่านมา ทาง Pyston ได้ออกชุดคำสั่งชื่อ
Pyston-lite ซึ่งเป็นส่วนขยายเสริมให้ Python ทำงานผ่าน JIT ได้
โดยส่วนขยายนี้จะทำให้่ Python ปกติสามารถทำงานได้เร็วขึ้นถึง 10-25%
โดยที่ไม่ต้องปรับแต่งโค้ดอะไรเลย (ขึ้นอยู่กับประเภทของงาน) และแถมทำงานบน
Mac M1 ได้อีกด้วย แต่การปรับแต่งจะไม่ครบถ้วนเท่ากับ Pyston ตัวเต็ม<span></span></p><a name='more'></a><br /><p></p><p>สำหรับเบื้องหลังการทำงาน ทาง Pyston ได้เขียนอธิบายว่า ได้ใช้ <a href="https://peps.python.org/pep-0523/" rel="nofollow" target="_blank">PEP 523 extension module</a>
ในการเขียนส่วนขยายสำหรับทำให้ CPython สามารถใช้งาน JIT ของ Pyston ได้
ก่อนหน้านี้ทางทีม Pyston ได้พัฒนา Pyston V2 เป็นส่วนขยาย
แต่ต่อมาพบว่าการ fork CPython ไปพัฒนาต่อ จะปรับปรุงประสิทธิภาพได้ดีกว่า
แต่การเปลี่ยนผ่านสำหรับผู้ใช้งานนั้นไม่ง่าย ทาง Pyston
เลยทำให้กลายเป็นส่วนขยายอีกครั้งในชื่อ Pyston-lite</p><p>เรามาลองใช้งาน Pyston-lite กัน!!!</p><p>ก่อนอื่น
การใช้งาน Pyston-lite ในตอนนี้รองรับเฉพาะ Python 3.8 กับระบบปฏิบัติการ
macOS/Linux เท่านั้น (X86 กับ arm) ติดตั้งผ่าน pip ด้วยคำสั่ง</p><p></p><blockquote>pip install pyston_lite_autoload</blockquote><p></p><p>หรือ<br /></p><p></p><blockquote>conda install pyston_lite_autoload -c pyston -c conda-forge</blockquote><p>โดยทาง
pyston_lite_autoload จะโหลด Pyston-lite
มาใช้งานกับโค้ดที่ต้องเร่งความเร็วให้เอง
แต่ถ้าเราต้องการให้มันทำงานตามที่เรากำหนด ให้ใส่</p><div style="background-color: #1e1e1e; color: #d4d4d4; font-family: Menlo, Monaco, "Courier New", monospace; font-size: 12px; font-weight: normal; line-height: 18px; white-space: pre;"><div><span style="color: #c586c0;">import</span><span style="color: #d4d4d4;"> pyston_lite</span></div><div><span style="color: #4ec9b0;">pyston_lite</span><span style="color: #d4d4d4;">.enable() </span></div></div><p></p><p></p><p>เข้าไปในโค้ดที่เราต้องการให้เร่งความเร็วได้เลย แต่อย่าลืมว่าขึ้นอยู่กับงาน บางงานที่ Pyston-lite สามารถเร่งความเร็วได้</p><p> </p><p>ผลลัพธ์จากการทดสอบ EC2 instances, either c6i.2xlarge or c6g.2xlarge, Ubuntu 20.04 AMI จากทาง Pyston </p><table><tbody><tr><td><br /></td><td>pyperformance x86</td><td>ARM</td><td>Pyston macrobenchmarks x86</td><td>ARM</td></tr><tr><td>Pyston 2.3.4</td><td>+66%</td><td>+54%</td><td>+35%</td><td>+25%</td></tr><tr><td>Pyston-lite 2.3.4</td><td>+28%</td><td>+25%</td><td>+8%</td><td>+8%</td></tr><tr><td>Pyston-lite 2.3.4 Mac</td><td>+27%</td><td>+39%</td><td>+8%</td><td>+5%</td></tr><tr><td>CPython 3.11.0b3</td><td>+15%</td><td>+10%</td><td>+8%</td><td>+5%</td></tr></tbody></table><p> </p><p>อ่านรายละเอียดเพิ่มเติมได้ที่ <a href="https://blog.pyston.org/2022/06/08/announcing-pyston-lite-our-python-jit-as-an-extension-module/" rel="nofollow" target="_blank">https://blog.pyston.org/2022/06/08/announcing-pyston-lite-our-python-jit-as-an-extension-module/ </a></p><p><br /></p><p>อ่านบทความ <a href="https://python3.wannaphong.com/2021/08/pyston-cpython.html">Pyston อีมพลีเมนต์ไพธอนที่เร็วกว่า CPython</a><br /></p>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-28553952093067335182022-05-19T08:06:00.007+07:002022-05-19T08:06:42.330+07:00Dependency Parser ภาษาไทยด้วย spaCy-Thai<p>สวัสดีผู้อ่านทุกท่านครับ บทความนี้ผมจะพาผู้อ่านไปทำ Dependency Parser ภาษาไทยด้วย spaCy-Thai กันครับ</p><span><a name='more'></a></span><h2 style="text-align: left;"><b>Dependency Parser คืออะไร</b></h2><p>Dependency Parser เป็นการระบุไวยากรณ์โครงสร้างของประโยคและค้นหาความสัมพันธ์ของคำ (1)</p><p>สำหรับภาษาไทย หลังจากที่เวลาผ่านมายาวนาน ในที่สุดก็มี Open Source สำหรับทำ Dependency Parser ภาษาไทย ชื่อว่า spaCy-Thai</p><h2 style="text-align: left;">spaCy-Thai</h2><p>spaCy-Thai เป็นไลบรารีในภาษา Python สำหรับทำ Dependency Parser ภาษาไทย พัฒนาโดยคุณ Koichi Yasuoka (2)</p><p></p><ul style="text-align: left;"><li>รองรับเฉพาะ Python 3</li><li>ใช้ MIT License</li></ul><div>สำหรับการติดตั้งทำได้ง่าย ๆ ผ่าน pypi: pip install spacy_thai</div><div><br /></div><div><b>การใช้งาน</b></div><div>ทำตามตัวอย่างนี้ได้เลย</div><p></p><div>>>> import spacy_thai</div><div><div>>>> nlp=spacy_thai.load()</div><div>>>> doc=nlp("แผนกนี้กำลังเผชิญกับความท้าทายใหม่")</div><div>>>> for t in doc:</div><div>... print("\t".join([str(t.i+1),t.orth_,t.lemma_,t.pos_,t.tag_,"_",str(0 if t.head==t else t.head.i+1),t.dep_,"_","_" if t.whitespace_ else "SpaceAfter=No"]))</div><div>...</div><div>1<span style="white-space: pre;"> </span>แผนก<span style="white-space: pre;"> </span>แผนก<span style="white-space: pre;"> </span>NOUN<span style="white-space: pre;"> </span>NCMN<span style="white-space: pre;"> </span>_<span style="white-space: pre;"> </span>4<span style="white-space: pre;"> </span>nsubj<span style="white-space: pre;"> </span>_<span style="white-space: pre;"> </span>SpaceAfter=No</div><div>2<span style="white-space: pre;"> </span>นี้<span style="white-space: pre;"> </span>นี้<span style="white-space: pre;"> </span>DET<span style="white-space: pre;"> </span>DDAC<span style="white-space: pre;"> </span>_<span style="white-space: pre;"> </span>1<span style="white-space: pre;"> </span>det<span style="white-space: pre;"> </span>_<span style="white-space: pre;"> </span>SpaceAfter=No</div><div>3<span style="white-space: pre;"> </span>กำลัง<span style="white-space: pre;"> </span>กำลัง<span style="white-space: pre;"> </span>AUX<span style="white-space: pre;"> </span>XVBM<span style="white-space: pre;"> </span>_<span style="white-space: pre;"> </span>4<span style="white-space: pre;"> </span>aux<span style="white-space: pre;"> </span>_<span style="white-space: pre;"> </span>SpaceAfter=No</div><div>4<span style="white-space: pre;"> </span>เผชิญ<span style="white-space: pre;"> </span>เผชิญ<span style="white-space: pre;"> </span>VERB<span style="white-space: pre;"> </span>VSTA<span style="white-space: pre;"> </span>_<span style="white-space: pre;"> </span>0<span style="white-space: pre;"> </span>ROOT<span style="white-space: pre;"> </span>_<span style="white-space: pre;"> </span>SpaceAfter=No</div><div>5<span style="white-space: pre;"> </span>กับ<span style="white-space: pre;"> </span>กับ<span style="white-space: pre;"> </span>ADP<span style="white-space: pre;"> </span>RPRE<span style="white-space: pre;"> </span>_<span style="white-space: pre;"> </span>6<span style="white-space: pre;"> </span>case<span style="white-space: pre;"> </span>_<span style="white-space: pre;"> </span>SpaceAfter=No</div><div>6<span style="white-space: pre;"> </span>ความ<span style="white-space: pre;"> </span>ความ<span style="white-space: pre;"> </span>PART<span style="white-space: pre;"> </span>FIXN<span style="white-space: pre;"> </span>_<span style="white-space: pre;"> </span>4<span style="white-space: pre;"> </span>obl<span style="white-space: pre;"> </span>_<span style="white-space: pre;"> </span>SpaceAfter=No</div><div>7<span style="white-space: pre;"> </span>ท้าทาย<span style="white-space: pre;"> </span>ท้าทาย<span style="white-space: pre;"> </span>VERB<span style="white-space: pre;"> </span>VACT<span style="white-space: pre;"> </span>_<span style="white-space: pre;"> </span>6<span style="white-space: pre;"> </span>acl<span style="white-space: pre;"> </span>_<span style="white-space: pre;"> </span>SpaceAfter=No</div><div>8<span style="white-space: pre;"> </span>ใหม่<span style="white-space: pre;"> </span>ใหม่<span style="white-space: pre;"> </span>ADV<span style="white-space: pre;"> </span>ADVN<span style="white-space: pre;"> </span>_<span style="white-space: pre;"> </span>7<span style="white-space: pre;"> </span>advmod<span style="white-space: pre;"> </span>_<span style="white-space: pre;"> </span>SpaceAfter=No</div><div>>>> import deplacy</div><div>>>> deplacy.render(doc,WordRight=True)</div><div> nsubj ╔════════>╔═ NOUN แผนก</div><div> det ║ ╚> DET นี้</div><div> aux ║ ╔════════> AUX กำลัง</div><div> ROOT ╚═╚═╔═══════ VERB เผชิญ</div><div> case ║ ╔════> ADP กับ</div><div> obl ╚>╚═╔═══ PART ความ</div><div> acl ╚>╔═ VERB ท้าทาย</div><div>advmod ╚> ADV ใหม่</div></div><div><br /></div><div>โดย spaCy-Thai ใช้ข้อมูล treebank ชื่อ <a href="https://github.com/UniversalDependencies/UD_Thai-PUD" rel="nofollow" target="_blank">Parallel Universal Dependencies จาก Universal Dependencies</a> มาเทรนโมเดล Dependency Parser ภาษาไทย สำหรับการทำงานเบื้องหลัง คือ ใช้ spaCy กับ udpipe ในการทำงานนั้นเอง</div><div><br /></div><div>Github: <a href="http://github.com/KoichiYasuoka/spaCy-Thai" rel="nofollow" target="_blank">github.com/KoichiYasuoka/spaCy-Thai</a></div><div><br /></div><div><b>อ้างอิง</b></div><div><div class="csl-bib-body" style="line-height: 1.35;">
<div class="csl-entry" style="clear: left; margin-bottom: 1em;">
<div class="csl-left-margin" style="float: left; padding-right: 0.5em; text-align: right; width: 1em;">1. </div><div class="csl-right-inline" style="margin: 0 .4em 0 1.5em;">Jaiswal S. Natural Language Processing — Dependency Parsing [Internet]. Medium. 2021 [cited 2022 May 19]. Available from: <a href="https://towardsdatascience.com/natural-language-processing-dependency-parsing-cf094bbbe3f7" rel="nofollow" target="_blank">https://towardsdatascience.com/natural-language-processing-dependency-parsing-cf094bbbe3f7</a></div>
</div>
<span class="Z3988" title="url_ver=Z39.88-2004&ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fzotero.org%3A2&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Adc&rft.type=webpage&rft.title=Natural%20Language%20Processing%20%E2%80%94%20Dependency%20Parsing&rft.description=Different%20ways%20for%20Dependency%20Parsing%20using%20spaCy%2C%20NLTK%20with%20Stanford%20CoreNLP%20and%20Stanza&rft.identifier=https%3A%2F%2Ftowardsdatascience.com%2Fnatural-language-processing-dependency-parsing-cf094bbbe3f7&rft.aufirst=Shivanee&rft.aulast=Jaiswal&rft.au=Shivanee%20Jaiswal&rft.date=2021-08-01&rft.language=en"></span>
<div class="csl-entry" style="clear: left;">
<div class="csl-left-margin" style="float: left; padding-right: 0.5em; text-align: right; width: 1em;">2. </div><div class="csl-right-inline" style="margin: 0 .4em 0 1.5em;">Yasuoka K. spaCy-Thai [Internet]. 2022 [cited 2022 May 19]. Available from: <a href="https://github.com/KoichiYasuoka/spaCy-Thai" rel="nofollow" target="_blank">https://github.com/KoichiYasuoka/spaCy-Thai</a></div>
</div>
<span class="Z3988" title="url_ver=Z39.88-2004&ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fzotero.org%3A2&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Adc&rft.type=computerProgram&rft.title=spaCy-Thai&rft.rights=MIT&rft.description=Dependency%20parser%20on%20Thai%20language&rft.identifier=https%3A%2F%2Fgithub.com%2FKoichiYasuoka%2FspaCy-Thai&rft.aufirst=Koichi&rft.aulast=Yasuoka&rft.au=Koichi%20Yasuoka&rft.date=2022-03-10"></span></div></div>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-19532470268590383322021-09-09T20:06:00.003+07:002021-09-09T20:06:37.583+07:00ทิปการเขียน Python: ตอนที่ 1 print ก็เขียนข้อมูลลงไฟล์ได้<p>สวัสดีครับทุกท่าน บทความนี้ผมจะมาแนะนำทิปการเขียน Python ตอนที่ 1 เกี่ยวกับคำสั่ง print ว่ามันทำอะไรได้มากกว่าแค่ print ในภาษา Python<br /><span></span></p><a name='more'></a><p></p><p><b>print สามารถเขียนไฟล์ได้</b></p><p>คำสั่ง print ในภาษา Python นอกจากจะใช้แสดงผลข้อมูลออกมาผ่านหน้าจอ ยังสามารถใช้เขียนข้อมูลลงไฟล์ได้พร้อมกับแสดงข้อมูลไปด้วย โดยสามารถทำได้ง่าย ๆ ดังนี้</p><div style="background-color: #fffffe; color: black; font-family: "monospace", Consolas, "Courier New", monospace; font-size: 14px; font-weight: normal; line-height: 19px; white-space: pre;"><div><span style="color: #af00db;">with</span><span style="color: black;"> </span><span style="color: #795e26;">open</span><span style="color: black;">(</span><span style="color: #a31515;">'test.txt'</span><span style="color: black;">, </span><span style="color: #a31515;">'w'</span><span style="color: black;">) </span><span style="color: #af00db;">as</span><span style="color: black;"> f:</span></div><div><span style="color: black;"> </span><span style="color: #795e26;">print</span><span style="color: black;">(</span><span style="color: #a31515;">"This line goes into a file."</span><span style="color: black;">, </span><span style="color: #001080;">file</span><span style="color: black;">=f) </span></div></div><p><br />ผลลัพธ์ในไฟล์ test.txt</p><p></p><blockquote>This line goes into a file.</blockquote>เราทำผ่าน file ของ print ได้<p></p><p> </p><p>ติดตามบทความต่อไปนะครับ</p><p>ขอบคุณครับ <br /></p>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-42955242371088126832021-08-27T11:53:00.002+07:002021-08-27T12:40:24.269+07:00Pyston อีมพลีเมนต์ไพธอนที่เร็วกว่า CPython<p>Pyston เป็นอีมพลีเมนต์ภาษาไพธอนที่มุ่งเน้นด้านประสิทธิภาพและสามารถใช้งานร่วมกันกับ CPython ได้[1] <span></span></p><a name='more'></a><p></p><p>เริ่มแรกตัว Pyston ถูกพัฒนาโดย Dropbox เมื่อปี ค.ศ.2014[1] แต่ยุติการพัฒนาในปี ค.ศ.2017[2] และต่อมาทางทีมงานได้นำมาพัฒนาต่อตั้งแต่ปี 2020[3]</p><p>ปัจจุบัน Pyston ถูกพัฒนาโดยอิง CPython 3.8.8 และรองรับการใช้งานบนลินุกซ์ X86-64 มีประสิทธิภาพมากกว่า CPython 30% ใน web server benchmarks โดยใช้หลักการคอมไพล์โค้ดด้วยเทคนิค JIT และสามารถใช้งานกับโมดูลที่ต้องคอมไพล์กับภาษา C อย่าง Numpy และอื่น ๆ ได้[4]</p><h2 style="text-align: left;">การใช้งาน Pyston<br /></h2><p>หลังจากการได้รู้จัก Pyston แล้ว ต่อไปเรามาลองใช้งาน Pyston กัน </p><div class="separator" style="clear: both; text-align: center;"><img alt="หน้า Pyston 2.3" border="0" data-original-height="672" data-original-width="1436" height="301" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJ4U2c0AXeaZ4iTkGsL494XZoxHJ1IDgJ3_byYHAdtqoqx0OZ6B1-usfMBarfDNXtCsdNrk9rzxqcDr1go5Vux0j1Z-WAFs1ON0h329BlRA8ITPIteZFuD4TqBW-sxR1OO6g0TmszjY_w/w640-h301/Screenshot+2021-08-27+113111.jpg" width="640" /></div><p>ผมได้ใช้ Ubuntu 20.04 โดยเลือก Pyston 2.3 จาก <a href="https://github.com/pyston/pyston/releases" rel="nofollow" target="_blank">https://github.com/pyston/pyston/releases</a> แล้วโหลดไฟล์ .deb ให้ตรงกับรุ่น Ubuntu ที่ใช้งาน<br /></p><p></p><blockquote><p>$ wget https://github.com/pyston/pyston/releases/download/v2.3/pyston_2.3_20.04.deb</p><p>$ sudo dpkg -i pyston_2.3_20.04.deb</p></blockquote><p>จากนั้น ลองเรียกใช้ด้วยคำสั่ง <code>pyston</code> กันได้เลย</p><p>$ pyston<br />Python 3.8.8 (heads/2.3_release:4b9a88fc50, Jul 8 2021, 15:46:12)<br />[Pyston 2.3.0, GCC 9.3.0] on linux<br />Type "help", "copyright", "credits" or "license" for more information.<br />>>></p><p>หากต้องการติดตั้งโมดูลจาก PyPI ให้ใช้คำสั่ง</p><p></p><blockquote>$ pyston -m pip install __โมดูลที่ต้องการ_</blockquote><p></p><p>ได้เลย</p><p><u><b>คำแนะนำ</b></u></p><p>แม้ว่า Pyston จะเข้ากันได้กับ CPython โดยสามารถใช้งานโมดูลที่คอมไพล์กับภาษาอื่น ๆ ได้ เช่น NumPy หรือ Pytorch เป็นต้น แต่อาจจะต้องคอมไพล์ใหม่ในการติดตั้ง ขอแนะนำให้ท่านที่ต้องการใช้งานให้ตั้งค่าคอมไพลเลอร์ให้เรียบร้อยก่อนใช้งาน</p><p><br /></p><p>ดูรายละเอียดเพิ่มเติม Pyston ได้ที่ <a href="https://github.com/pyston/pyston" rel="nofollow" target="_blank">https://github.com/pyston/pyston</a></p><p><b>อ้างอิง</b></p><p>[1] Dropbox เปิดตัว Pyston, ไพธอนที่คอมไพล์ด้วย LLVM: <a href="https://www.blognone.com/node/55056" rel="nofollow" target="_blank">https://www.blognone.com/node/55056</a></p><p>[2] Dropbox pulls the plug on faster Python project: <a href="https://www.infoworld.com/article/3162800/dropbox-pulls-the-plug-on-faster-python-project.html" rel="nofollow" target="_blank">https://www.infoworld.com/article/3162800/dropbox-pulls-the-plug-on-faster-python-project.html</a></p><p>[3] Pyston โครงการภาษาไพธอนประสิทธิภาพสูง เปิดเป็นโอเพนซอร์สแล้ว: <a href="https://www.blognone.com/node/122539" rel="nofollow" target="_blank">https://www.blognone.com/node/122539</a></p><p>[4] Pyston v2.2: faster and open source: <a href="https://blog.pyston.org/2021/05/05/pyston-v2-2-faster-and-open-source/" rel="nofollow" target="_blank">https://blog.pyston.org/2021/05/05/pyston-v2-2-faster-and-open-source/</a><br /></p>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-81161193391430475182021-08-08T13:39:00.004+07:002021-08-08T13:39:59.609+07:00Jython กับ IronPython กำลังจะรองรับ Python 3<p>หลังจากที่ทั้ง Jython กับ IronPython รองรับเฉพาะ Python 2.7 มานาน แม้ว่าทาง PSF จะยุติการสนับสนุน CPython 2.7 ไปนานแล้ว ล่าสุดในปีนี้ทั้งโครงการ Jython ซึ่งเป็นโครงการนำภาษา Python ไปรันบน Java กับโครงการ IronPython ซึ่งเป็นอีกโครงการนำ Python ไปรันบน .NET ทั้งสองโครงการได้มีการเคลื่อนไหวเกี่ยวกับ Python 3 แล้ว<span></span></p><a name='more'></a><p></p><p></p><div class="separator" style="clear: both; text-align: center;"><img border="0" data-original-height="837" data-original-width="880" height="304" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEisOylXGcszNNi0bl6pU1sEuVFXUUi7EgpaRJ9uehG0aic5PdJeO-MTzj3KP8Npr6Yi7ful4Va7gcadNJP2Cns1DQdeCC0OEjm2pgMM4muj5lBcDmGK-JxdOWgy19_oLGJ7nOTN6RTV_Q0/w320-h304/Screenshot+2021-08-08+132601.jpg" title="Jython 3" width="320" /></div>Jython เป็นโครงการนำภาษา Python ไปรันบน Java เริ่มมีการพัฒนาให้ Jython รองรับ Python 3.8 โดยมีรายละเอียดขึ้นที่หน้าเว็บของ Jython โดยเวลาเรียกใช้งาน ให้เรียกด้วย Jython3 และพัฒนาบน Java 11 รองรับการรันบนหลาย OS และล่าสุด ทางนักพัฒนา Jython ได้ส่ง pull request บน GitHub ของ Jython ให้รองรับ Python 3.8<p></p><p></p><ul style="text-align: left;"><li>รายละเอียดบนเว็บ Jython: <a href="https://www.jython.org/jython-3-mvp.html" rel="nofollow" target="_blank">https://www.jython.org/jython-3-mvp.html</a></li><li>Implementation of the data model for v3.8: <a href="https://github.com/jython/jython/pull/107" rel="nofollow" target="_blank">https://github.com/jython/jython/pull/107</a></li></ul><p>ต่อมา โครงการ IronPython เป็นโครงการนำ Python ไปรันบน .NET มีการออกรุ่น alpha1 ของ IronPython 3.4 แล้วเมื่อเดือนเมษายนที่ผ่านมา โดยยังรองรับเฉพาะ Python 3.4 สามารถทำงานได้บน .NET Framework 4.6, .NET Core 2.1, .NET Core 3.1 และ .NET 5<br /></p><div class="separator" style="clear: both; text-align: center;"><img border="0" data-original-height="887" data-original-width="1308" height="271" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiUHg2VclTsD1RV1V0cBwLwXRPmfOPeF4Ti_sYhqrLnGBygnIfVmYp7wPPs9VQm9cWztjNQpBjdLV_VjtxYhqmd2cWW2VlNx5K66OU3uNVnQZ_U7Iz3tsFv7P3YjxWcvqBTu7_p0K9ti6g/w400-h271/Screenshot+2021-08-08+133453.jpg" title="IronPython website" width="400" /></div><p>สำหรับกระบวนการพัฒนาโครงการ IronPython กำลังพัฒนา IronPython 3.4-beta กับ 3.5 alpha อยู่</p><ul style="text-align: left;"><li>IronPython 3.4 alpha1: <a href="https://github.com/IronLanguages/ironpython3/releases/tag/v3.4.0-alpha1" rel="nofollow" target="_blank">https://github.com/IronLanguages/ironpython3/releases/tag/v3.4.0-alpha1</a></li><li><a href="https://python3.wannaphong.com/2015/03/ironpython-3-python-3-windows.html" target="_blank">ใช้ IronPython 3 กับ Python 3 บน Windows</a> <br /></li></ul>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-13925913760469953382021-06-21T01:26:00.003+07:002021-06-21T01:32:07.672+07:00รันโค้ดโปรแกรมแบบ sandbox กับ Docker ด้วย Python<p></p><div class="separator" style="clear: both; text-align: center;"><img border="0" data-original-height="477" data-original-width="1537" height="198" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhAk3RCHb2tbEhZtOrEecevYJcr-00AzRQ47knOG60YWxGotVjyrQ_-noGT6WdA-NG0Mr-Le0cJmmt4ugL-BH-wcMeVYMU-XxRiPFu8s5bow3T7yHDAwYnkeG9q5yt4YjvpLyqIaAI5hw4/w640-h198/epicbox.jpg" title="รันโค้ดโปรแกรมแบบ sandbox กับ Docker ด้วย Python" width="640" /></div>สวัสดีผู้อ่านทุกท่านครับ บทความนี้ผมจะพาผู้อ่านไปเขียนโปรแกรมภาษา python เพื่อรันโค้ดโปรแกรมแบบ sandbox กับ Docker ด้วย Python แบบง่าย ๆ กันครับ<p></p><a name='more'></a><blockquote>ก่อนอื่นผมขอบอกว่าบทความนี้สามารถทำงานได้เฉพาะบน Linux เท่านั้นครับ (Mac OS ไม่ได้ทดสอบ และ Windows ไม่สามารถรันได้)</blockquote>Docker เป็นชุดซอฟต์แวร์สำหรับทำคอนเทนเนอร์ที่นักพัฒนาทั่วโลกรู้จักกันดี ณ เวลานี้ส่วนใหญ่คงขึ้นระบบโดยใช้ docker กันเกือบหมดแล้ว ด้วยความง่ายและรักษาความเข้ากันได้ของโปรแกรมที่เรารัน<p></p><p>เราสามารถใช้ docker รันโปรแกรมแบบ sandbox กันได้ ซึ่งบทความนี้ผมจะพาผู้อ่านไปเขียนโปรแกรมบนภาษา python สำหรับรันโค้ดภาษาต่าง ๆ แบบ sandbox กับ Docker บน Linux กันแบบง่าย ๆ ครับ</p><p>ก่อนอื่นให้ผู้อ่านทำการติดตั้ง docker บน Linux ให้เรียบร้อยก่อน</p><p></p><blockquote>สามารถอ่านคู่มือการติดตั้ง Docker ได้ที่ <a href="https://docs.docker.com/engine/install/" rel="nofollow" target="_blank">docs.docker.com/engine/install/</a></blockquote>หลังจากนั้น ให้ลง python3 พร้อมกับ pip3 ให้เรียบร้อย<p></p><p>บทความนี้เราจะใช้ไลบรารีที่ชื่อว่า epicbox</p><p>epicbox เป็นไลบรารีบนภาษา Python สำหรับรันโค้ดที่ไม่น่าเชื่อถือ มาแยกรันใน docker ซึ่งมันถูกใช้เป็นระบบตรวจคำตอบอัตโนมัติของระบบตรวจสอบคำตอบเขียนโค้ดของเว็บ Stepik.org และใช้ MIT License</p><p>เอาล่ะ ต่อไปเรามาลองรันโค้ดง่าย ๆ ใน docker แบบ sandbox กันเลย</p><p>เราจะลองโค้ดโปรแกรมภาษา python แบบ sandbox กัน โดยผมจะใช้ python 3.6<br /></p><p>ก่อนอื่น ให้ดึง image มาเก็บไว้โดยใช้คำสั่ง </p><p></p><blockquote>docker pull python:3.6.5-alpine</blockquote><p></p><p>แล้วใช้คำสั่ง</p><p></p><blockquote>pip install epicbox</blockquote><p></p><p>จากนั้น เรามาเขียนโปรแกรมรันโค้ด python ใน docker แบบ sandbox กัน<br /></p><p><code>import epicbox<br /><br />epicbox.configure(<br /> profiles=[<br /> epicbox.Profile('python', 'python:3.6.5-alpine')<br /> ]<br />)<br />files = [{'name': 'main.py', 'content': b'print(42)'}]<br />limits = {'cputime': 1, 'memory': 64}<br />result = epicbox.run('python', 'python3 main.py', files=files, limits=limits)<br />print(result) <br /></code></p><p>แล้วรัน ผลลัพธ์</p><p></p><blockquote>{'exit_code': 0, 'stdout': b'42\n', 'stderr': b'', 'duration': 0.042068, 'timeout': False, 'oom_killed': False}</blockquote><p></p><p>จะเห็นได้ว่า ผลลัพธ์จะแสดงออกมาเป็น dict การแสดงผลผ่านหน้าจอออกมาอยู่ในคีย์ stdout รวมถึงระยะเวลาการรัน และอื่น ๆ ต่อไป เรามาลองให้รันโค้ดภาษา python โดยมี input อยู่ภายในกัน</p><p><code>import epicbox<br /><br />epicbox.configure(<br /> profiles=[<br /> epicbox.Profile('python', 'python:3.6.5-alpine')<br /> ]<br />)<br />files = [{'name': 'main.py', 'content': b'print(input())'}]<br />limits = {'cputime': 1, 'memory': 64}<br />result = epicbox.run('python', 'python3 main.py', files=files, limits=limits,stdin="แมว".encode('utf-8'))<br />print(result)</code></p><p>ผลลัพธ์</p><p></p><blockquote>{'exit_code': 0, 'stdout': b'\xe0\xb9\x81\xe0\xb8\xa1\xe0\xb8\xa7\n', 'stderr': b'', 'duration': 0.110464, 'timeout': False, 'oom_killed': False}</blockquote><p></p><p>หรือ</p><p></p><blockquote>{'exit_code': 0, 'stdout': b'แมว\n', 'stderr': b'', 'duration': 0.110464, 'timeout': False, 'oom_killed': False}</blockquote><p></p><p>หากเราต้องการรันหลายไฟล์ก็แค่เพิ่มไฟล์เข้าไปใน files ได้ด้วย</p><p><code>import epicbox<br /><br />epicbox.configure(<br /> profiles=[<br /> epicbox.Profile('python', 'python:3.6.5-alpine')<br /> ]<br />)<br />files = [<br /> {'name': 'main.py', 'content': b'import cal\nprint(cal.plue(1,2))'},<br /> {'name': 'cal.py', 'content': b'def plue(a,b):\n return a+b'},<br />]<br />limits = {'cputime': 1, 'memory': 64}<br />result = epicbox.run('python', 'python3 main.py', files=files, limits=limits)<br />print(result)</code></p><p>ผลลัพธ์</p><p></p><blockquote>{'exit_code': 0, 'stdout': b'3\n', 'stderr': b'', 'duration': 0.036982, 'timeout': False, 'oom_killed': False}</blockquote><p></p><p>จะเห็นได้ว่าเราสามารถเรียก import ไฟล์อื่นได้ด้วย ซึ่งเราสามารถจำกัด cpu เวลาในการรัน รวมถึงพื้นที่ memory ในการรันโค้ดได้ด้วย</p><p>ซึ่งเราสามารถเรียกใช้งาน docker ตามภาษาที่เราต้องการรันได้เลย แถมสามารถรันโค้ดภาษา c โดยสามารถคอมไพล์แล้วรันได้ด้วย เหมาะกับผู้ที่ต้องการรันโค้ดที่ไม่น่าเชื่อถือ และต้องการความปลอดภัย โดยสามารถนำไปใช้สร้างระบบตรวจคำตอบจากการรันโค้ดสำหรับระบบฝึกเขียนโปรแกรมได้ด้วย</p><p>อ่านเอกสารเพิ่มเติมได้ที่ <a href="https://github.com/StepicOrg/epicbox">https://github.com/StepicOrg/epicbox</a><br /></p><p></p><p></p>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-84088121309527197112021-05-22T12:44:00.006+07:002021-05-22T12:44:55.974+07:00ดีบั๊กโค้ดภาษา Python แบบไม่ต้องใช้ print/log ด้วย icecream🍦 <p>สวัสดีผู้อ่านทุกท่านครับ หลาย ๆ ท่านเวลาดีบั้กโค้ดภาษา Python หลายท่านอาจจะใช้คำสั่ง print หรือ log ออกมาดูผลลัพธ์ในโค้ดเพื่อดูว่ามันเป็นไปตามค่าที่ต้องการไหม บทความนี้ผมจะมาเสนออีกวิธีในการดีบั้กโค้ด Python โดยการใช้งาน icecream🍦 กันครับ</p><a name='more'></a><br /><p></p><p>การดีบั๊กโค้ดเป็นขั้นตอนหนึ่งที่ขาดไม่ได้ในการเขียนโปรแกรมคอมพิวเตอร์ สำหรับ Python เราสามารถใช้คำสั่ง print / log ในการดีบั๊กได้ แต่อาจจะไม่ค่อยเหมาะสมนัก ผมขอเสนอไลบรารี icecream🍦 ในการดีบั๊กโค้ด Python ของเรากัน</p><p>ไลบรารี icecream🍦 เป็นไลบรารีช่วยในการดีบั๊กโค้ด Python ให้สะดวกยิ่งขึ้น จากเดิมคำสั่ง print หรือ log อาจบอกข้อมูลไม่ละเอียดนัก แต่ไลบรารีตัวนี้สามารถช่วยดีบั๊กโค้ดรวมถึงข้อมูลเข้าและออกของฟังก์ชันได้ด้วย</p><p><b>การติดตั้ง</b> ใช้คำสั่ง</p><p></p><blockquote>pip install icecre </blockquote><p></p><p><b>ตัวอย่างการเรียกใช้งาน</b></p><p>เรียกใช้ไลบรารีด้วยคำสั่ง <br /></p><div style="background-color: #fffffe; color: black; font-family: 'monospace', Consolas, 'Courier New', monospace; font-size: 14px; font-weight: normal; line-height: 19px; white-space: pre;"><div><span style="color: #af00db;">from</span><span style="color: black;"> icecream </span><span style="color: #af00db;">import</span><span style="color: black;"> ic</span></div></div><p>ถ้าผมมีฟังก์ชัน plus ใช้ในการบวกเลขของ Python</p><div style="background-color: #fffffe; color: black; font-family: 'monospace', Consolas, 'Courier New', monospace; font-size: 14px; font-weight: normal; line-height: 19px; white-space: pre;"><div><span style="color: blue;">def</span><span style="color: black;"> </span><span style="color: #795e26;">plus</span><span style="color: black;">(</span><span style="color: #001080;">x1</span><span style="color: black;"> , </span><span style="color: #001080;">x2</span><span style="color: black;">):</span></div><div><span style="color: black;"> </span><span style="color: #af00db;">return</span><span style="color: black;"> x1 + x2</span></div></div><p>สามารถดีบั๊กได้ด้วยคำสั่ง</p><div style="background-color: #fffffe; color: black; font-family: 'monospace', Consolas, 'Courier New', monospace; font-size: 14px; font-weight: normal; line-height: 19px; white-space: pre;"><div><span style="color: black;">ic(plus(</span><span style="color: #09885a;">5</span><span style="color: black;">, </span><span style="color: #09885a;">1</span><span style="color: black;">))</span></div></div><p>ผลลัพธ์</p><div><div class="stream output-id-14 output_text"><pre>ic| plus(5, 1): 6
</pre></div><div class="pyout output-id-15 output_text"><pre>6</pre></div></div><p> </p><p>ความสามารถเยอะมาก แนะนำให้เข้าไปอ่านเอกสารได้ที่ <a href="https://github.com/gruns/icecream" rel="nofollow" target="_blank">https://github.com/gruns/icecream</a> <br /></p>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-16859541229788731602021-04-09T00:43:00.005+07:002021-04-09T01:04:51.281+07:00RustPython ว่าที่รันไทม์ Python แทน CPython 🐍<div class="separator" style="clear: both; text-align: center;"><img border="0" data-original-height="560" data-original-width="1485" height="242" imageanchor="1" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGDyxnd6uSqAu8ZBnjlq3pOkqUDtHa31NzZt3KTVZO6P05pZqgjdraRnU8Mhcr2gl0dkHmwsASnmnCoxLcdcfD5K5KiAmhn-Dcvs4TR1soIyQh81F0uAPxYX4_5cHh25tK7U6Og_2GgaI/w640-h242/rust-python.png" style="margin-left: 1em; margin-right: 1em;" title="RustPython ว่าที่รันไทม์ Python แทน CPython 🐍" width="640" /></div><br /><p></p><p>นับตั้งแต่ภาษา Python ได้ถือกำเนิดมาพร้อมกับการพัฒนา CPython ที่พัฒนา Python บนภาษา C ตลอดเวลาที่ผ่านมา มี implementation อื่น ๆ ได้แก่ Jython ที่นำ Python ไปรันบน Java, IronPython ที่นำ Python ไปรันบน .NET</p><a name='more'></a><p></p><p style="text-align: center;"><iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube-nocookie.com/embed/MMLsPg4dOVM" title="YouTube video player" width="560"></iframe><br /></p><p>จนการมาของกระแสภาษา Rust ล่าสุดในปี ค.ศ.2018 ได้มีกลุ่มนักพัฒนา พยายามนำภาษา Python ไปรันบนภาษา Rust ด้วยโครงการที่ชื่อว่า RustPython<br /></p><p></p><div class="separator" style="clear: both; text-align: center;"><img alt="โลโก้ RustPython" border="0" data-original-height="253" data-original-width="775" height="130" imageanchor="1" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi6Kd-c3lCOhczTEgEs1_0XeOM0h28mJKcZm8x9R1OIe_4cFEQoFU06H4oRMuSRnxCKfc7h5Irehj7zBQzVn6v0u85QRUfvt2MwIOnOQ10dTFooVbe2twwDMn55Mp26TEDnv3cwJ7IbiH0/w400-h130/rustpython.jpg" style="margin-left: 1em; margin-right: 1em;" title="RustPython ว่าที่รันไทม์ Python แทน CPython 🐍" width="400" /></div><p></p><p>RustPython เป็น Interpreter ภาษา Python บนภาษา Rust โดยสามารถรันโค้ดโปรแกรมภาษา Python บน Rust ได้และสามารถแปลงไปเป็น WebAssembly ได้แถมมีความสามารถด้าน JIT และ VM<br /></p><p>สำหรับ RustPython ปัจจุบันยังอยู่ในช่วงกำลังพัฒนา โดยมีเป้าหมายคือ สามารถรันโค้ด Python อย่างเต็มรูปแบบได้บนภาษา Rust และมีคุณสมบัติ เร็ว เชื่อถือได้ และปลอดภัย สามารถใช้งานได้จาก Rust และคอมไพล์ไปเป็น WebAssembly ได้ [1]<br /></p><p></p><div class="separator" style="clear: both; text-align: center;"><img border="0" data-original-height="271" data-original-width="481" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg9wNuYwAaOnUJsPuAB_aLtRJt4myV4O92DlEWpku9-bn4-HCkEHoPyYqD1Gc7cJIJQ2_S1xZqprq3fk9kwFLf6IXfJkrJ1KFYAFMPWljCYJsuIiqMZxwQgQAhnBwJ6qltQZmAOStzZ-Uo/s320/Screenshot+2021-04-08+231828.jpg" style="margin-left: 1em; margin-right: 1em;" width="320" /></div>เรามาลองใช้ RustPython กัน<p></p><p>ก่อนอื่นให้เราไปติดตั้ง Rust ก่อน โดยเข้าไปที่ <a href="https://www.rust-lang.org/tools/install" rel="nofollow" target="_blank">rust-lang.org/tools/install</a> จากนั้นโหลดมาติดตั้งให้เรียบร้อย</p><p>จากนั้นให้เรา clone โปรเจคมา</p><p></p><blockquote>git clone https://github.com/RustPython/RustPython</blockquote><p></p><p>แล้วสั่ง cd แล้วลอง build แสดงผลลัพธ์ไฟล์ demo.py<br /></p><p></p><blockquote><p>cd RustPython</p><p>cargo run --release demo.py </p></blockquote><p>ถ้าได้ผลลัพธ์ แสดงว่าสามารถ build ได้อย่างถูกต้อง</p><p></p><blockquote>Hello, RustPython!</blockquote><p>จากนั้น เราลอง interactive shell ได้ด้วยคำสั่ง</p><p></p><blockquote>cargo run --release</blockquote><p></p><p>จะได้โหมดสำหรับรับคำสั่งผ่านแป้นพิมพ์ <br /></p><p></p><blockquote>Welcome to the magnificent Rust Python 0.1.2 interpreter 😱 🖖<br />No previous history.<br />>>>>></blockquote><p>สามารถติดตั้งเพื่อเรียกใช้งานได้ด้วยคำสั่ง</p><p></p><blockquote>cargo install --path ./</blockquote><p></p><p>แล้วเราสามารถไปเรียกใช้คำสั่ง rustpython ที่ไหนก็ได้ในเครื่อง</p><p></p><blockquote># rustpython<br />Welcome to the magnificent Rust Python 0.1.2 interpreter 😱 🖖<br />No previous history.<br />>>>>></blockquote><p></p><h2 style="text-align: left;">การใช้งาน Python บน RustPython</h2><div class="separator" style="clear: both; text-align: center;"><img alt="การใช้งาน Python บน RustPython" border="0" data-original-height="481" data-original-width="905" height="341" imageanchor="1" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhGfI_NtW4OyLBupZOayaUmvwPjQG-vhXxv26r8-BoVoXTPit9E4KzWuegDFdnTnBcp003vRereu-7HGTNqQG4gBbyq8u6hviR5l7Jq7nVE7SLvE1zbyCUplnzbM-0WK1weoXwz3sMYN7w/w640-h341/Screenshot+2021-04-09+010305.jpg" style="margin-left: 1em; margin-right: 1em;" width="640" /></div>RustPython ปัจจุบันถูกพัฒนาบนฐาน Python 3.8 โดยทั่วไปสามารถใช้งานได้เหมือน python ตามปกติ<p></p><blockquote>>>>>> i = input()<br />test<br />>>>>> print(i)<br />test<br />>>>>> แมว = 1<br />>>>>> แมว * 2<br />2</blockquote><p></p><p>และสามารถเรียกใช้งานไลบรารีพื้นฐานต่าง ๆ ได้บนฐาน Python 3.8<br /></p><p></p><blockquote>>>>>> import math<br />>>>>> math.pi<br />3.141592653589793</blockquote><p>นอกจากนั้น ยังสามารถลองเล่น RustPython แบบออนไลน์ได้ด้วย (ผ่าน WebAssembly)</p><div class="separator" style="clear: both; text-align: center;"><img border="0" data-original-height="937" data-original-width="1898" height="316" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjANNEvh3-6hZxP8HE6CKVmiyNVr4eeTBazFKcmUDZAcVMNWIQZ4f2cozfbn_4Att74pwVCeuFrafailztuYqlls32xfgyRhCkNVl76314rZYpvSe8OvvBGqhTMxNt-Dw4T3wxkEmnev1U/w640-h316/Screenshot_2021-04-09+RustPython+Demo.png" style="margin-left: 1em; margin-right: 1em;" width="640" /></div>คลิกได้ที่ <a href="https://rustpython.github.io/demo/" rel="nofollow" target="_blank">rustpython.github.io/demo/</a><br /><p><br /></p><p></p><p></p><h2 style="text-align: left;">ความเข้ากันได้ RustPython กับ CPython</h2><p>RustPython ได้มีระบบทดสอบกับชุดทดสอบของ Python สำหรับทดสอบความเข้ากันได้ของโค้ดภาษา Python ซึ่งปัจจุบัน RustPython ทำผ่านไปแล้ว 71.81%</p><div class="separator" style="clear: both; text-align: center;"><img alt="ความเข้ากันได้ RustPython กับ CPython" border="0" data-original-height="937" data-original-width="1898" height="317" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5HK_DT3gkWVIu7cDrbQskJfbew0URtzTf1lH8JPXalZcjwqAqQtre2UU3vdc1jjuPdtuIpTxZZumLmAir6Wo02c4AexMRuMXo55h74h0vZWz6vpggS3h4fI_DvFa3a6tGq5bSWzRWOkg/w640-h317/Screenshot_2021-04-08+Regression+test+results.png" style="margin-left: 1em; margin-right: 1em;" width="640" /></div>สามารถดูรายละเอียดได้ที่ <a href="https://rustpython.github.io/pages/regression-tests-results.html" rel="nofollow" target="_blank">rustpython.github.io/pages/regression-tests-results.html</a><br /><p>และเมื่อไม่นานมานี้ RustPython เพิ่งรองรับ PIP [5]<br /></p><h2 style="text-align: left;">ประสิทธิภาพของ RustPython<br /></h2><p></p><table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto;"><tbody><tr><td style="text-align: center;"><img alt="ผลการวัดประสิทธิภาพ RustPython เทียบกับ Python 3" border="0" data-original-height="873" data-original-width="1060" height="330" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiMOcsKeynVmOPwi3UGdmP0gIdmWFnMHetMwWa9u9FqeyYzKHK3q23xBhvZmvwUT5ET5IBl3mKhZDWsdi-RwaYZkH8i_FiVIqeEpg0Gkcb5wY6pMO_zEduvf1OxE33kPIoYw4zo47oxhMQ/w400-h330/Screenshot+2021-04-08+233328.jpg" style="margin-left: auto; margin-right: auto;" width="400" /></td></tr><tr><td class="tr-caption" style="text-align: center;">ผลการวัดประสิทธิภาพ RustPython เทียบกับ Python 3<br />ที่มา <a href="https://pybenchmarks.org/u64q/rustpython.php" rel="nofollow" target="_blank">pybenchmarks.org/u64q/rustpython.php</a></td></tr></tbody></table><p>ณ ปัจจุบันที่เขียนบทความ ประสิทธิภาพของ RustPython ยังสู้ CPython 3 ไม่ได้ (อาจเรียกได้ว่า CPython ปกติเร็วกว่าหลายเท่าตัว) [2] ซึ่งอาจต้องใช้เวลาพัฒนาอีกสักระยะหนึ่งในการปรับปรุงประสิทธิภาพในกระบวนการพัฒนา</p><p>ท่านใดสนใจอยากร่วมพัฒนาหรืออยากลอง RustPython สามารถเข้าไปได้ที่ <a href="https://github.com/RustPython/RustPython" rel="nofollow" target="_blank">https://github.com/RustPython/RustPython</a></p><p>ขอขอบคุณ ปู Ferris จาก <a href="https://rustacean.net/" rel="nofollow" target="_blank">rustacean.net </a>และรูปอีโมจิงูจาก Microsoft<br /></p><p><b>บรรณานุกรม</b><br /></p><div class="csl-bib-body" style="line-height: 1.35;">
<div class="csl-entry" style="clear: left; margin-bottom: 1em;">
<div class="csl-left-margin" style="float: left; padding-right: 0.5em; text-align: right; width: 1em;">1. </div><div class="csl-right-inline" style="margin: 0px 0.4em 0px 1.5em;">Why RustPython? [Internet]. RustPython. [cited 2021 Apr 9]. Available from: <a href="https://rustpython.github.io/" rel="nofollow" target="_blank">https://rustpython.github.io/</a></div>
</div>
<span class="Z3988" title="url_ver=Z39.88-2004&ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fzotero.org%3A2&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Adc&rft.type=webpage&rft.title=Why%20RustPython%3F&rft.description=An%20open%20source%20Python%203%20(CPython%20%3E%3D%203.5.0)%20interpreter%20written%20in%20Rust%20%F0%9F%90%8D%20%F0%9F%98%B1%20%F0%9F%A4%98&rft.identifier=https%3A%2F%2Frustpython.github.io%2F&rft.language=en"></span>
<div class="csl-entry" style="clear: left; margin-bottom: 1em;">
<div class="csl-left-margin" style="float: left; padding-right: 0.5em; text-align: right; width: 1em;">2. </div><div class="csl-right-inline" style="margin: 0px 0.4em 0px 1.5em;">RustPython vs Python 3 | Python Interpreters Benchmarks [Internet]. [cited 2021 Apr 9]. Available from: <a href="https://pybenchmarks.org/u64q/rustpython.php" rel="nofollow" target="_blank">https://pybenchmarks.org/u64q/rustpython.php</a></div>
</div>
<span class="Z3988" title="url_ver=Z39.88-2004&ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fzotero.org%3A2&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Adc&rft.type=webpage&rft.title=RustPython%C2%A0vs%C2%A0Python%203%20%7C%20Python%C2%A0Interpreters%C2%A0Benchmarks&rft.identifier=https%3A%2F%2Fpybenchmarks.org%2Fu64q%2Frustpython.php"></span>
<div class="csl-entry" style="clear: left; margin-bottom: 1em;">
<div class="csl-left-margin" style="float: left; padding-right: 0.5em; text-align: right; width: 1em;">3. </div><div class="csl-right-inline" style="margin: 0px 0.4em 0px 1.5em;">RustPython · RustPython/RustPython [Internet]. GitHub. [cited 2021 Apr 9]. Available from: <a href="https://github.com/RustPython/RustPython" rel="nofollow" target="_blank">https://github.com/RustPython/RustPython</a></div>
</div>
<span class="Z3988" title="url_ver=Z39.88-2004&ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fzotero.org%3A2&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Adc&rft.type=webpage&rft.title=RustPython%20%C2%B7%20RustPython%2FRustPython&rft.description=A%20recent%20change%20probably%20made%20the%20interpreter%20extremely%20slow%2C%20this%20can%20be%20demonstrated%20by%20a%20simple%20benchmark%3A%20%23%20On%20current%20master%20cargo%20build%20target%2Fdebug%2Frustpython%20tests%2Fsnippets%2Fstrings.py%202.25s...&rft.identifier=https%3A%2F%2Fgithub.com%2FRustPython%2FRustPython&rft.language=en"></span>
<div class="csl-entry" style="clear: left; margin-bottom: 1em;">
<div class="csl-left-margin" style="float: left; padding-right: 0.5em; text-align: right; width: 1em;">4. </div><div class="csl-right-inline" style="margin: 0px 0.4em 0px 1.5em;">RustPython: a Python implementation in Rust [Internet]. [cited 2021 Apr 9]. Available from: <a href="https://archive.fosdem.org/2019/schedule/event/rust_python/" rel="nofollow" target="_blank">https://archive.fosdem.org/2019/schedule/event/rust_python/</a></div>
</div>
<span class="Z3988" title="url_ver=Z39.88-2004&ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fzotero.org%3A2&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Adc&rft.type=webpage&rft.title=RustPython%3A%20a%20Python%20implementation%20in%20Rust&rft.rights=http%3A%2F%2Fcreativecommons.org%2Flicenses%2Fby-sa%2F2.0%2Fbe%2F&rft.identifier=https%3A%2F%2Farchive.fosdem.org%2F2019%2Fschedule%2Fevent%2Frust_python%2F&rft.language=en"></span>
<div class="csl-entry" style="clear: left;">
<div class="csl-left-margin" style="float: left; padding-right: 0.5em; text-align: right; width: 1em;">5. </div><div class="csl-right-inline" style="margin: 0px 0.4em 0px 1.5em;">pip is working! 🎉 🎉 [Internet]. RustPython. 2021 [cited 2021 Apr 9]. Available from: <a href="https://rustpython.github.io/blog/2021/01/26/pip-support.html" rel="nofollow" target="_blank">https://rustpython.github.io/blog/2021/01/26/pip-support.html</a></div>
</div>
<span class="Z3988" title="url_ver=Z39.88-2004&ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fzotero.org%3A2&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Adc&rft.type=webpage&rft.title=pip%20is%20working!%20%F0%9F%8E%89%20%F0%9F%8E%89&rft.description=7380%20commits%20and%201940%20pull%20requests%20later%2C%20pip%20and%20get-pip.py%20are%20working%20with%20RustPython%20%F0%9F%8E%89%20%F0%9F%8E%89.%20pip%20can%20install%20itself%20and%20setuptools!&rft.identifier=https%3A%2F%2Frustpython.github.io%2Fblog%2F2021%2F01%2F26%2Fpip-support.html&rft.date=2021-01-26&rft.language=en"></span>
</div>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-88164228622861007352021-02-27T15:22:00.007+07:002021-02-27T15:23:42.791+07:00ทำ Zero-shot classification ข้อความภาษาไทยง่าย ๆ ด้วย transformers + Python<p>สวัสดีผู้อ่านทุกท่านครับ บทความนี้ผมจะพาผู้อ่านไปทำ Zero-shot classification ข้อความภาษาไทยง่าย ๆ ด้วย transformers + Python กันครับ<span></span></p><a name='more'></a><p></p><h2 style="text-align: left;">Zero-shot classification คืออะไร?</h2><p>Zero-shot classification เป็นความสามารถในการตรวจจับประเภทโดยที่ไม่ผ่านการฝึกฝนแบบจำลองมาก่อน คล้ายกับมนุษย์ที่สามารถแยกประเภทสิงของที่แตกต่างกันได้โดยที่ไม่มีการสอนหรือเรียนมาก่อน [3]<br /></p><p>ตัวอย่างเช่น</p><p>ประโยค: แมวกำลังเดินไปหาเจ้าของ</p><p>ประโยค: ใครเป็นคนรับผิดชอบเรื่องนี้</p><p>ประโยค: พวกเราไม่ได้ทำอะไรผิด</p><p>ประเภท: ประโยคบอกเล่า ประโยคคำถาม ประโยคปฎิเสธ</p><p>มนุษย์เราสามารถจำแนกประเภทประโยคเหล่านี้ได้ทันที เหมือนกับ Zero-shot classification ที่สามารถแบ่งประเภทได้โดยไม่ต้องนำข้อมูลประเภทงานที่ต้องการไปฝึกสอนกับแบบจำลองก่อน และไม่ต้องทำการถ่ายโอนความรู้ (Transfer Learning) โดยฝึกสอนเพียงแบบจำลองเดียวสำหรับ Zero-shot classification</p><h2 style="text-align: left;">การทำ Zero-shot classification ข้อความภาษาไทย</h2><p><br />สำหรับการทำ Zero-shot classification ข้อความภาษาไทย ปัจจุบันเราสามารถทำ Zero-shot classification ได้ง่าย ๆ โดยใช้ชุดคำสั่ง transformers ซึ่งเป็นชุดคำสั่งด้านการประมวลผลภาษาธรรมชาติที่ได้รับความนิยมอย่างสูงในปัจจุบัน</p><p>สำหรับบทความนี้จะพาไปทำ Zero-shot classification ข้อความภาษาไทยด้วย แบบจำลอง xlm-roberta-large-xnli</p><p>แบบจำลอง xlm-roberta-large-xnli เป็นแบบจำลองที่ถูกฝึกฝนสำหรับงานด้าน zero-shot text classification ใช้แบบจำลอง xlm-roberta-large [2] ในการฝึกฝน โดยใช่ชุดข้อมูล XNLI: The Cross-Lingual NLI Corpus ซึ่งมีภาษาไทยอยู่ในชุดข้อมูลด้วย [1]<br /></p><p></p><blockquote>อ่านรายละเอียดเพิ่มเติมได้จากอ้างอิงข้างล่างบทความ</blockquote><p></p><p>สำหรับการเขียนโปรแกรมภาษา Python เพื่อทำ Zero-shot classification ข้อความภาษาไทย นั้น</p><p>ก่อนอื่นให้ติดตั้งชุดคำสั่งที่ต้องใช้ผ่าน pypi ด้วยคำสั่ง</p><p></p><blockquote>pip install transformers sentencepiece </blockquote>เมื่อติดตั้งเสร็จ ได้เวลาเขียนโปรแกรมทำ Zero-shot classification<p></p><p>
<code>from transformers import pipeline<br />classifier = pipeline("zero-shot-classification", model="joeddav/xlm-roberta-large-xnli")<br />text = "เราไม่ได้ทำ" #ประโยคที่ต้องการให้แยกประเภท ทดลอง: สินค้าชิ้นนี้ราคาเท่าไร,เรารักคุณ,ทำไมชีวิตต้องมาเจออะไรแบบนี้ แย่มาก ๆ, เราไม่ได้ทำ<br />candidate_labels = ["ประโยคคำถาม", "ประโยคบอกเล่า", "ประโยคปฏิเสธ"] # ประเภทที่เราต้องการให้แยกประเภท<br />print(classifier(text, candidate_labels))</code>
</p><p><b>ผลลัพธ์</b></p><p></p><blockquote>{'labels': ['ประโยคปฏิเสธ', 'ประโยคบอกเล่า', 'ประโยคคำถาม'],<br /> 'scores': [0.8681947588920593, 0.08875910192728043, 0.04304611682891846],<br /> 'sequence': 'เราไม่ได้ทำ'}</blockquote><p></p><p>จะเห็นได้ว่า Zero-shot classification สามารถแยกประเภทข้อความภาษาไทยได้ง่าย ๆ และมี scores ค่อนข้างดี</p><p>แนะนำก่อนนำไปใช้งานให้ทดลองกันใช้งานจริง และประเมินกับวิธีฝึกฝนแบบจำลองอื่น ๆ ด้วย</p><p>อ้างอิง</p><div class="csl-bib-body" style="line-height: 1.35;">
<div class="csl-entry" style="clear: left; margin-bottom: 1em;">
<div class="csl-left-margin" style="float: left; padding-right: 0.5em; text-align: right; width: 1em;">1. </div><div class="csl-right-inline" style="margin: 0px 0.4em 0px 1.5em;">joeddav/xlm-roberta-large-xnli · Hugging Face [Internet]. [cited 2021 Feb 27]. Available from: <a href="https://huggingface.co/joeddav/xlm-roberta-large-xnli" rel="nofollow" target="_blank">https://huggingface.co/joeddav/xlm-roberta-large-xnli</a></div>
</div>
<span class="Z3988" title="url_ver=Z39.88-2004&ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fzotero.org%3A2&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Adc&rft.type=webpage&rft.title=joeddav%2Fxlm-roberta-large-xnli%20%C2%B7%20Hugging%20Face&rft.description=We%E2%80%99re%20on%20a%20journey%20to%20solve%20and%20democratize%20artificial%20intelligence%20through%20natural%20language.&rft.identifier=https%3A%2F%2Fhuggingface.co%2Fjoeddav%2Fxlm-roberta-large-xnli"></span>
<div class="csl-entry" style="clear: left; margin-bottom: 1em;">
<div class="csl-left-margin" style="float: left; padding-right: 0.5em; text-align: right; width: 1em;">2. </div><div class="csl-right-inline" style="margin: 0px 0.4em 0px 1.5em;">Conneau A, Khandelwal K, Goyal N, Chaudhary V, Wenzek G, Guzmán F, et al. Unsupervised Cross-lingual Representation Learning at Scale. arXiv:191102116 [cs] [Internet]. 2020 Apr 7 [cited 2021 Feb 27]; Available from: <a href="http://arxiv.org/abs/1911.02116" rel="nofollow" target="_blank">http://arxiv.org/abs/1911.02116</a></div>
</div>
<span class="Z3988" title="url_ver=Z39.88-2004&ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fzotero.org%3A2&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&rft.genre=article&rft.atitle=Unsupervised%20Cross-lingual%20Representation%20Learning%20at%20Scale&rft.jtitle=arXiv%3A1911.02116%20%5Bcs%5D&rft.aufirst=Alexis&rft.aulast=Conneau&rft.au=Alexis%20Conneau&rft.au=Kartikay%20Khandelwal&rft.au=Naman%20Goyal&rft.au=Vishrav%20Chaudhary&rft.au=Guillaume%20Wenzek&rft.au=Francisco%20Guzm%C3%A1n&rft.au=Edouard%20Grave&rft.au=Myle%20Ott&rft.au=Luke%20Zettlemoyer&rft.au=Veselin%20Stoyanov&rft.date=2020-04-07"></span>
<div class="csl-entry" style="clear: left;">
<div class="csl-left-margin" style="float: left; padding-right: 0.5em; text-align: right; width: 1em;">3. </div><div class="csl-right-inline" style="margin: 0px 0.4em 0px 1.5em;">Chaudhary A. Zero Shot Learning for Text Classification [Internet]. Amit Chaudhary. 2020 [cited 2021 Feb 27]. Available from: <a href="https://amitness.com/2020/05/zero-shot-text-classification/" rel="nofollow" target="_blank">https://amitness.com/2020/05/zero-shot-text-classification/</a></div>
</div>
<span class="Z3988" title="url_ver=Z39.88-2004&ctx_ver=Z39.88-2004&rfr_id=info%3Asid%2Fzotero.org%3A2&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Adc&rft.type=webpage&rft.title=Zero%20Shot%20Learning%20for%20Text%20Classification&rft.description=A%20summary%20of%20%E2%80%9CTrain%20Once%2C%20Test%20Anywhere%E2%80%9D%20paper%20for%20zero-shot%20text%20classification&rft.identifier=https%3A%2F%2Famitness.com%2F2020%2F05%2Fzero-shot-text-classification%2F&rft.aufirst=Amit&rft.aulast=Chaudhary&rft.au=Amit%20Chaudhary&rft.date=2020-05-31&rft.language=en"></span>
</div><p></p>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-15928413167299957322020-11-05T13:13:00.002+07:002020-11-05T13:13:28.713+07:00ดึงข้อมูลโพสต์จากทวิตเตอร์ง่าย ๆ ด้วย Python<p>สวัสดีผู้อ่านทุกท่านครับ หลังจากที่เราไป<a href="https://python3.wannaphong.com/2020/10/facebook-facebook-python.html">ดึงข้อมูลโพสต์จากเพจ Facebook และกลุ่ม Facebook ด้วย Python</a> กันแล้ว ในบทความนี้เราจะไปดึงข้อมูลโพสต์จากทวิตเตอร์กันครับ<span></span></p><a name='more'></a><p></p><p>ทวิตเตอร์ (Twitter) เป็นเครือข่ายสังคมออนไลน์ที่มีข่าวสารรวดเร็วกว่าสำนักข่าวต่าง ๆ และมีอิทธิพลต่อวงการต่าง ๆ ไม่ว่าเป็นการเมือง สังคม โดยแค่โพสต์สั้น ๆ กับใส่ # ซึ่งวัยรุ่นใช้งานกันมาก จึงเป็นแหล่งข้อมูลที่ใช้อธิบายปรากฎการณ์ต่าง ๆ เหตุการณ์ต่าง ๆ ได้</p><p>ในการดึงข้อมูลจากทวิตเตอร์มีหลายวิธี ผมขอแนะนำแค่โมดูลที่ชื่อว่า Twitter Scraper</p><p>Twitter Scraper เป็นโมดูลในภาษา Python สำหรับดึงข้อมูลจากเว็บทวิตเตอร์จากหน้าเว็บโดยตรง</p><p>สามารถติดตั้งได้ด้วยคำสั่ง pip install twitter_scraper</p><p><b>ตัวอย่างการใช้งาน</b></p><p></p><blockquote>>>> from twitter_scraper import get_tweets<br />>>> <br />>>> for tweet in get_tweets('twitter', pages=1):<br />... print(tweet['text'])<br />... </blockquote><p></p><p>อ่านเอกสารเพิ่มได้ที่ <a href="https://github.com/bisguzar/twitter-scraper" rel="nofollow" target="_blank">https://github.com/bisguzar/twitter-scraper</a><br /></p>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-41892340909737916052020-10-21T02:27:00.002+07:002020-10-21T08:36:49.311+07:00ดึงข้อมูลโพสต์จากเพจ Facebook และกลุ่ม Facebook ง่าย ๆ ด้วย Python<p>สวัสดีผู้อ่านทุกท่านครับ บทความนี้เราจะมาเขียนโปรแกรมภาษา Python เพื่อดึงข้อมูลโพสต์จากเพจ Facebook และกลุ่ม Facebook มาเก็บไว้เพื่อใช้ในการประมวลผลต่อไปครับ</p><a name='more'></a><p></p><p>Facebook เป็นเครือข่ายสังคมออนไลน์ที่ได้รับความนิยมมากที่สุดในประเทศไทย จึงทำให้สื่อต่าง ๆ อยู่บน Facebook จำนวนมาก เช่น สำนักข่าวต่าง ๆ เป็นต้น นิยมอยู่บนเพจ Facebook หรือ กลุ่ม Facebook แต่กลับไม่ค่อยได้ปรับปรุงข้อมูลบนเว็บไซต์ของตัวเอง</p><p>นักวิจัย คนทำ NLP ภาษาไทย หรือผู้ที่ทำงานด้าน Data Science ที่ต้องการข้อมูลเหล่านั้น จึงต้องหาวิธีดึงข้อมูลโพสต์จากเพจ Facebook ด้วยตัวเอง ไม่ว่าเป็นใช้ Open API ของ Facebook ซึ่งทางผู้ขียนได้หาเครื่องมือไลบรารีในภาษา Python สำหรับช่วยดึงข้อมูลโพสต์จากเพจ Facebook มาเก็บไว้แบบง่าย ๆ โดยใช้ไลบรารีที่ชื่อว่า Facebook Scraper</p><p>Facebook Scraper เป็นเครื่องมือสำหรับช่วยดึงข้อมูลโพสต์จากเพจ Facebook ในภาษา Python โดยที่ไม่ต้องป้อน API Key ในการดึงข้อมูลเลย</p><p>ความสามารถ</p><ul style="text-align: left;"><li>สามารถดึงข้อมูลจากเพจ Facebook ได้พร้อมรายละเอียดโพสต์ เช่น ข้อความในโพสต์ วันเวลาที่โพสต์ จำนวนการถูกใจ จำนวนความคิดเห็น ลิงก์รูปภาพ และลิงค์วิดีโอ เป็นต้น<br /></li><li>สามารถดึงข้อมูลจากกลุ่ม Facebook ได้ <br /></li><li>สามารถ login ด้วย Facebook ได้ เหมาะกับดึงข้อมูลจากกลุ่มปิด</li></ul><p><b>การติดตั้ง</b> สามารถติดตั้งได้ผ่านคำสั่ง <code>pip install facebook-scraper</code></p><p><b>การใช้งาน</b></p><p>ให้เรียกใช้งานด้วยคำสั่ง </p><div style="background-color: #fffffe; color: black; font-family: monospace, Consolas, "Courier New", monospace; font-size: 14px; font-weight: normal; line-height: 19px; white-space: pre;"><div><span style="color: #af00db;">from</span><span style="color: black;"> facebook_scraper </span><span style="color: #af00db;">import</span><span style="color: black;"> get_posts</span></div></div><p> คำสั้่ง</p><p></p><blockquote> get_posts(<br /> account: Optional[str] = None,<br /> group: Union[str, int, None] = None,<br /> credentials: Optional[Credentials] = None,<br /> **kwargs,<br />):<br /> Args:<br /> account (str): The account of the page.<br /> group (int): The group id.<br /> credentials (Optional[Tuple[str, str]]): Tuple of email and password to login before scraping.<br /> timeout (int): Timeout for requests.<br /> page_limit (int): How many pages of posts to go through.<br /> Use None to try to get all of them.<br /> extra_info (bool): Set to True to try to get reactions.<br /> youtube_dl (bool): Use Youtube-DL for video extraction. </blockquote><p></p><ul style="text-align: left;"><li>ดึงข้อมูลจากเพจ Facebook ใช้คำสั่ง <code>get_posts(account = 'ชื่อเพจ', pages=จำนวนหน้าสูงสุด)</code><br /></li><li>ดึงข้อมูลจากกลุ่ม Facebook ใช้คำสั่ง <code>get_posts(group='ไอดีของกลุ่มบน Facebook', pages=จำนวนหน้าสูงสุด) </code> </li><li>การเข้าสู่ระบบ (กรณีต้องการดึงจากกลุ่มหรือเพจที่จำกัดการเข้าถึง)
ใช้คำสั่ง get_posts(____, credentials = ('user','password') ,
pages=จำนวนหน้าสูงสุด)</li></ul><p>จำนวนหน้าสูงสุด คือ จำนวนหน้าสูงสุดที่ดึงจาก Facebook </p><p>ทดลองเล่นบน Google Colab ได้ที่ <a href="https://colab.research.google.com/drive/1KWTbfnwVU9w2qGgXisHu97fNp0PHuGia?usp=sharing" rel="nofollow" target="_blank">https://colab.research.google.com/drive/1KWTbfnwVU9w2qGgXisHu97fNp0PHuGia?usp=sharing</a><br /></p><p><b>ตัวอย่างการดึงข้อมูลจากเพจ Facebook</b></p><p>ผมขอยกตัวอย่างการดึงข้อมูลจากเพจ PyThaiNLP <br /></p><div style="background-color: #fffffe; color: black; font-family: monospace, Consolas, "Courier New", monospace; font-size: 14px; font-weight: normal; line-height: 19px; white-space: pre;"><div><span style="color: #af00db;">for</span><span style="color: black;"> post </span><span style="color: blue;">in</span><span style="color: black;"> get_posts(account = </span><span style="color: #a31515;">'pythainlp'</span><span style="color: black;">, pages=</span><span style="color: #09885a;">1</span><span style="color: black;">):</span></div><div><span style="color: black;"> </span><span style="color: #795e26;">print</span><span style="color: black;">(post)</span></div></div><p>ผลลัพธ์</p><p></p><blockquote>{'comments': 0,<br /> 'image': None,<br /> 'images': [],<br /> 'likes': 0,<br /> 'link': 'https://github.com/PyThaiNLP/thaigov-v2-corpus',<br /> 'post_id': None,<br /> 'post_text': '',<br /> 'post_url': 'https://facebook.com/story.php?story_fbid=2661181230787414&id=408004796247683',<br /> 'shared_text': 'Tontan Wannaphong Phatthiyaphaibun shared a link to the '<br /> 'group: Thai Natural Language Processing.\n'<br /> '19 September at 00:11 ·',<br /> 'shares': 0,<br /> 'text': 'Tontan Wannaphong Phatthiyaphaibun shared a link to the group: Thai '<br /> 'Natural Language Processing.\n'<br /> '19 September at 00:11 ·',<br /> 'time': None,<br /> 'user_id': None,<br /> 'video': None,<br /> 'video_id': None,<br /> 'video_thumbnail': None}</blockquote><br /><p></p><p><b>ตัวอย่างการดึงข้อมูลจากกลุ่ม Facebook</b></p><p>ผมขอยกตัวอย่างกลุ่ม Thai NLP</p><div style="background-color: #fffffe; color: black; font-family: monospace, Consolas, "Courier New", monospace; font-size: 14px; font-weight: normal; line-height: 19px; white-space: pre;"><div><span style="color: #af00db;">for</span><span style="color: black;"> post </span><span style="color: blue;">in</span><span style="color: black;"> get_posts(group=</span><span style="color: #a31515;">'408004796247683'</span><span style="color: black;">, pages=</span><span style="color: #09885a;">1</span><span style="color: black;">):</span></div><div><span style="color: black;"> pprint(post)</span></div></div><p>ผลลัพธ์</p><p></p><blockquote>{'comments': 3,<br /> 'image': None,<br /> 'images': [],<br /> 'likes': 6,<br /> 'link': None,<br /> 'post_id': '1189541251427363',<br /> 'post_text': 'ผมสามารถโหลด TSynC-1 (Thai Speech Corpus for Speech Synthesis '<br /> 'version 1) ตัวเต็ม จำนวน 13.94 hours โดยมีจำนวนประโยค 5,200 '<br /> 'ประโยคได้จากช่องทางไหนครับ?',<br /> 'post_url': None,<br /> 'shared_text': '',<br /> 'shares': 0,<br /> 'text': 'ผมสามารถโหลด TSynC-1 (Thai Speech Corpus for Speech Synthesis '<br /> 'version 1) ตัวเต็ม จำนวน 13.94 hours โดยมีจำนวนประโยค 5,200 '<br /> 'ประโยคได้จากช่องทางไหนครับ?',<br /> 'time': datetime.datetime(2020, 10, 14, 18, 13, 52),<br /> 'user_id': '100006866895771',<br /> 'video': None,<br /> 'video_id': None,<br /> 'video_thumbnail': None}</blockquote><p></p><p><br /></p><p>เพียงเท่านี้เราก็จะได้ dict ของข้อมูลโพสต์ทั้งจากกลุ่มบน Facebook และเพจบน Facebook เพื่อนำไปประมวลผลต่อไปได้ด้วยครับ</p><p>นอกจากนั้น Facebook Scraper รองรับการใช้งานผ่าน CLI ด้วย โดยที่ไม่ต้องเขียนโปรแกรม</p><p>สามารถอ่านเอกสารได้ที่ <a href="https://github.com/kevinzg/facebook-scraper" rel="nofollow" target="_blank">https://github.com/kevinzg/facebook-scraper</a><br /></p>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com2tag:blogger.com,1999:blog-2940971822351202057.post-39702258774219473272020-09-11T18:58:00.001+07:002022-07-01T01:15:49.641+07:00pyenv แก้ปัญหารุ่นของ Python แบบง่าย ๆ<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="473" data-original-width="550" height="275" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhCZ_Id0sFEaPbMmjWBeLn4ruD3JDNtmbZeXcC3Kuzu7ligTM_-7U-EvZkYMQhrI6plwB_TEq1Y-EcRXBrIcDh7JlCedFw1veoVwWOBUuNHS_0Q9T3GWC3CsfN5dHA7OgtHZqkw_JdwINA/s320/1.JPG" title="pyenv แก้ปัญหารุ่นของ Python แบบง่าย ๆ" width="320" /></div>
สวัสดีนักพัฒนาโปรแกรมทุก ๆ ท่านนะครับ หลายคนที่ใช้ภาษา Python อาจจะเจอปัญหาเรื่อง รุ่นของ Python ที่แตกต่างกันเวลาพัฒนา เช่น สมมติ เราพัฒนาบน Python 3.8 แล้วต้องการทดสอบว่าใช้งานบน Python 3.6 ได้ไหม ซึ่งหลายคนต้องลง Python หลายรุ่นในเครื่องเดียวกัน เพื่อทดสอบความเข้ากันได้ของโค้ดที่เขียนด้วย Python และหลายคนจำเป็นต้องใช้โค้ดโปรแกรมที่เขียนบน Python 2.7 ที่หมดการสนับสนุนไปแล้ว เนื่องจากไม่ได้ port มา Python 3 ยิ่งทำให้ปัญหารุ่นของ Python ยิ่งสับสนยิ่งขึ้นเวลาเรียกคำสั่ง python<br />
<a name='more'></a><br />
<br />
ทางออกของปัญหานี้ที่ง่าย ๆ คือ ใช้ pyenv<br />
<br />
pyenv เป็นเครื่องมือสำหรับจัดการรุ่นของ Python แบบง่าย ๆ รองรับการสลับรุ่นของ python รองรับทั้ง macOS และ Linux โดยสำหรับ Windows จะใช้ในชื่อ pyenv-win<br />
<br />
<b>การติดตั้ง</b><br />
สำหรับ Windows ให้เปิด Powershell ขึ้นแล้ว ใช้คำสั่ง<br />
<blockquote class="tr_bq">
pip install pyenv-win --target $HOME\.pyenv</blockquote>
macOS ใช้คำสั่ง<br />
<blockquote class="tr_bq">
brew update<br />
brew install pyenv</blockquote>
สำหรับ linux สาย Debain/Ubuntu ทำตามเอกสาร <a href="https://www.liquidweb.com/kb/how-to-install-pyenv-on-ubuntu-18-04/" rel="nofollow" target="_blank">https://www.liquidweb.com/kb/how-to-install-pyenv-on-ubuntu-18-04/</a> ได้เลย<br />
<br />
นอกจากติดตั้งเสร็จแล้ว เรามาใช้งาน python หลายรุ่นแบบง่าย ๆ ด้วย pyenv กันครับ<br />
<br />
<b>การใช้งานเบื้องต้น </b><br />
<br />
ก่อนอื่นให้อัปเดตรายชื่อ python ด้วยคำสั่ง<br />
<blockquote class="tr_bq">
pyenv update</blockquote>
ดูรายชื่อรุ่น python ที่มีทั้งหมดได้ด้วยคำสั่ง<br />
<blockquote class="tr_bq">
pyenv install -l</blockquote>
เอาล่ะ เรามาลง Python รุ่นต่าง ๆ กัน<br />
<br />
สมมติ ตอนนี้ผมใช้ Python 3.7.4 อยู่ ต้องการไปใช้ Python 3.8.5 ก่อนอื่นผมต้องลง Python 3.8.2 ก่อน (เฉพาะในครั้งแรก) ด้วยคำสั่ง<br />
<blockquote class="tr_bq">
pyenv install 3.8.5</blockquote>
แล้วใช้คำสั่ง<br />
<blockquote class="tr_bq">
pyenv global 3.8.5</blockquote>
เพียงเท่านี้ เราก็สลับมาใช้งาน Python 3.8.5 เรียบร้อยแล้วแบบง่าย ๆ นอกจากนั้น pyenv ยังรองรับการลงหลายรุ่นในคราวเดียวกัน เช่น ลง Python 3.8.5 กับ Python 3.7.4<br />
<blockquote class="tr_bq">
pyenv install 3.8.5 3.7.4</blockquote>
<u>สรุป</u> pyenv แก้ปัญหารุ่นของ Python แบบง่าย ๆ โดยทำให้การสลับรุ่นของ Python ทำให้ง่ายและสะดวกกว่าเดิม<br />
<br />
อ่านเอกสารการใช้งาน pyenv ได้ที่ <a href="https://github.com/pyenv/pyenv" rel="nofollow" target="_blank">https://github.com/pyenv/pyenv</a><br />
และอ่านเอกสารของ pyenv-win สำหรับผู้ใช้งานบน Windows ได้ที่ <a href="https://github.com/pyenv-win/pyenv-win" rel="nofollow" target="_blank">https://github.com/pyenv-win/pyenv-win</a>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-9527436693775094322020-09-07T23:01:00.000+07:002020-09-07T23:01:31.846+07:00ตัดคำภาษาลาวด้วย LaoNLPสวัสดีผู้อ่านทุกท่านครับ ผมได้พัฒนาเครื่องมือสำหรับประมวลผลภาษาลาวขึ้นมา ชื่อว่า LaoNLP โดยเป็นโปรเจคที่ผมทำในเวลาว่าง โดยตอนนี้รองรับการตัดคำภาษาลาว และตัดประโยคภาษาลาว<br />
<a name='more'></a><br />
LaoNLP เป็นโปรเจคที่ผมพัฒนาขึ้นมาเพื่อช่วยประมวลผลภาษาลาวใน Python ซึ่งเป็นภาษาทางการที่ถูกใช้ในประเทศลาว<br />
<br />
เนื่องจากผมค้นหาเครื่องมือสำหรับประมวลผลภาษาลาวแล้วพบว่าภาษาลาวไม่ค่อยมีเครื่องมือด้านนี้เท่าไร จึงพัฒนาขึ้นมา<br />
<br />
โดยติดตั้งได้ง่าย ๆ ด้วยคำสั่ง pip install laonlp<br />
<br />
<b>การใช้งาน</b><br />
ตัดคำ<br />
<blockquote class="tr_bq">
from laonlp.tokenize import word_tokenize<br />txt= ""<br />print(word_tokenize("ພາສາລາວໃນປັດຈຸບັນ.")) # ['ພາສາລາວ', 'ໃນ', 'ປັດຈຸບັນ', '.']</blockquote>
ส่วนตัดประโยค<br />
<blockquote class="tr_bq">
from laonlp.tokenize import sent_tokenize<br />txt= ""<br />print(word_tokenize("ພາສາລາວໃນປັດຈຸບັນ.ພາສາລາວໃນປັດຈຸບັນ.")) # ['ພາສາລາວໃນປັດຈຸບັນ',ພາສາລາວໃນປັດຈຸບັນ]</blockquote>
<br />
อ่านรายละเอียดเพิ่มเติมได้ที่ <a href="https://github.com/wannaphong/LaoNLP" rel="nofollow" target="_blank">https://github.com/wannaphong/LaoNLP</a>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-31035008794093385182020-07-18T23:15:00.002+07:002020-07-18T23:23:41.212+07:00ดึงข้อมูลตำบล อำเภอ จังหวัดจากที่อยู่ง่าย ๆ ด้วย ThaiAddressParser<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="219" data-original-width="913" height="152" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhmGMBs2LSm0rTJpwAJVG2cFY-y-nizy63wHpExV8m33TGw-UOQ8EoaRXQQdK4-6V1-edFpe21_jVVMJu7Bi55QQAEDNqniLz7OKAPDBTlCyOE2dAqj-8gY8ide8i4_aVsCoTQlazajUwc/s640/a02.jpg" title="ดึงข้อมูลตำบล อำเภอ จังหวัดจากที่อยู่ง่าย ๆ ด้วย ThaiAddressParser" width="640" /></div>
สวัสดีผู้อ่านทุกท่านครับ บทความนี้ผมจะพาผู้อ่านไปเขียนโปรแกรมดึงข้อมูลตำบล อำเภอ จังหวัดจากที่อยู่แบบข้อความง่าย ๆ ด้วย ThaiAddressParser กันครับ<br />
<a name='more'></a><br />
สมมติ คุณได้ข้อมูลแบบตัวอย่างนี้<br />
<blockquote class="tr_bq">
มหาวิทยาลัยขอนแก่น วิทยาเขตหนองคาย 112 หมู่ 7 บ้านหนองเดิ่น ตำบลหนองกอมเกาะ อำเภอเมือง จังหวัดหนองคาย</blockquote>
มาในแบบ Text จำนวนมาก บรรทัดละที่อยู่ โดยที่ไม่ได้มีการแยกฟิลด์ที่อยู่อย่างข้อมูล ตำบล อำเภอ และจังหวัดมาให้ คุณอาจจะนึกถึงต้องเขียนโปรแกรมมาแยกด้วยตัวของคุณเอง<br />
<br />
แต่ได้มีนักพัฒนาคนหนึ่งชื่อ LI Shuai จาก Shopee Singapore ได้พัฒนาโปรแกรมแยกข้อมูลตำบล อำเภอ จังหวัดจากที่อยู่แบบข้อความออกมาในชื่อโมดูล ThaiAddressParser<br />
<br />
ThaiAddressParser เป็นโมดูลสำหรับใช้แยกข้อมูลตำบล อำเภอ จังหวัดจากที่อยู่แบบข้อความออกมาให้แบบง่าย ๆ แถมข้อมูลตำบล อำเภอ จังหวัด ที่ได้ออกมา ได้ทั้งภาษาไทยกับภาษาอังกฤษออกมาด้วย โดยอาศัยข้อมูลจากวิกิพีเดีย และใช้ MIT License<br />
<br />
<b>การติดตั้ง</b><br />
สามารถติดตั้งได้โดยใช้คำสั่ง<br />
<blockquote class="tr_bq">
pip install ThaiAddressParser</blockquote>
<br />
<b>การใช้งาน</b><br />
สามารถใช้แยกข้อมูลตำบล อำเภอ จังหวัดจากที่อยู่แบบข้อความออกมาให้แบบง่าย ๆ ตามตัวอย่างนี้ได้เลย<br />
<pre>import ThaiAddressParser
address = "มหาวิทยาลัยขอนแก่น วิทยาเขตหนองคาย 112 หมู่ 7 บ้านหนองเดิ่น ตำบลหนองกอมเกาะ อำเภอเมือง จังหวัดหนองคาย"
print(ThaiAddressParser.parse(address))</pre>
<br />
<u>ผลลัพธ์</u><br />
<pre>{'district': {'en': 'Mueang Nong Khai', 'thai': 'เมืองหนองคาย'},
'original_address': 'มหาวิทยาลัยขอนแก่น วิทยาเขตหนองคาย 112 หมู่ 7 บ้านหนองเดิ่น ตำบลหนองกอมเกาะ อำเภอเมือง จังหวัดหนองคาย',
'parsed_address': 'มหาวิทยาลัยขอนแก่น วิทยาเขตหนองคาย 112 หมู่ 7 บ้านหนองเดิ่น ต.หนองกอมเกาะ อ.เมืองหนองคาย จ.หนองคาย',
'province': {'en': 'Nong Khai', 'thai': 'หนองคาย'},
'remaining_address': 'มหาวิทยาลัยขอนแก่น วิทยาเขตหนองคาย 112 หมู่ 7 บ้านหนองเดิ่น',
'sub_district': {'en': 'Nong Kom Ko', 'thai': 'หนองกอมเกาะ'}} </pre>
<br />
Google Colab สำหรับลองรัน : <a href="https://colab.research.google.com/drive/1QOJY15CFwRW2d2JSW-bugUaeIdqEfAtE?usp=sharing" rel="nofollow" target="_blank">colab.research.google.com/drive/1QOJY15CFwRW2d2JSW-bugUaeIdqEfAtE?usp=sharing</a><br />
<br />
สามารถเข้าไปดู GitHub ของ ThaiAddressParser ได้ที่ <a href="https://github.com/HandsomeBrotherShuaiLi/ThaiAddressParser" rel="nofollow" target="_blank">github.com/HandsomeBrotherShuaiLi/ThaiAddressParser</a>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-68238859898148472072020-06-14T20:57:00.003+07:002020-06-14T22:35:52.243+07:00เขียน Quantum Machine Learning ได้ด้วย PennyLane<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="564" data-original-width="1338" height="268" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjwBsDazVV2lnZ_wp4rkZ_DZOZ5joo05U7zRm-djaffM5zFhMi1pcdQZ9mPwxgicdSPME9GrwIH9PXfKQkKa-eBduaLDwkHJQCWLRNk-7B_Aeq17FB_iP7Sr-6SURDStmBXmXyxrmWN-HY/s640/Annotation+2020-06-14+204454.jpg" title="เขียน Quantum Machine Learning ได้ด้วย PennyLane" width="640" /></div>
<br />
สวัสดีผู้อ่านทุกท่านครับ บทความนี้จะพาผู้อ่านไปรู้จัก Quantum Machine Learning เบื้องต้น และแนะนำเครื่องมือสำหรับศึกษาและทำ Quantum Machine Learning ชื่อ PennyLane<br />
<a name='more'></a><br />
<br />
<h3>
Quantum Machine Learning คืออะไร? </h3>
Quantum Machine Learning (การเรียนรู้เชิงควอนตัม) เป็นการนำ Quantum Computing มาประยุกต์กับ Machine Learning ตัวอย่างเช่น เราจะสามารถนำควอนตัมคอมพิวเตอร์มาช่วยในการประมวลผล AI ได้รึไม่ เป็นต้น<br />
<br />
<b>วิดีโอแนะนำ </b><br />
<div style="text-align: center;">
<iframe width="560" height="315" src="https://www.youtube.com/embed/hWx2Rws3L-A" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<br />
<br />
<div style="text-align: left;">
เรียนรู้เกี่ยวกับ Quantum Machine Learning เพิ่มเติมได้ที่ <a href="https://pennylane.ai/qml/" rel="nofollow" target="_blank">https://pennylane.ai/qml/ </a></div>
</div>
<hr />
<h3>
PennyLane</h3>
<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="20" data-original-width="301" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPXrTjxs9cOTCPIOh3mxNPkSKDYWmKtX0TubsdqqnvcSlF2FqhtYXeq9IUl9KzrUePpRm7E_lV5Ie6ICuCSExtS8Pm_S4fMxhI5KBWlMbXKbvzFjwek1i7VyZfDJcDzGRdX3T1yOduqbs/s1600/pennylane.png" title="โลโก้ PennyLane" /></div>
<br />
ด้วยเหตุนี้จึงมี Startup ชื่อ Xanadu มาทำ Startup ที่เกี่ยวกับ Quantum Machine Learning โดยสร้างโมดูลสำหรับงาน Quantum Machine Learning ชื่อ PennyLane<br />
<br />
PennyLane เป็นโมดูลที่ช่วยเราสร้าง Quantum Machine Learning โดยรองรับการเชื่อมทำงานกับ PyTorch กับ TensorFlow และอื่น ๆ และรองรับการทำงานบนอุปกรณ์ควอนตัมจริง ๆ อีกด้วย เช่น IBM Q และอื่น ๆ (ถ้ารันบนคอมพิวเตอร์ทั่วไปจะทำงานบน simulate ด้วย StrawberryFields สำหรับจำลอง continuous variable quantum optical circuits) แถมยังใช้ Apache 2.0 License<br />
<br />
อ่าน paper ของ PennyLane ได้ที่ <a href="https://arxiv.org/abs/1811.04968" rel="nofollow" target="_blank">https://arxiv.org/abs/1811.04968</a><br />
<br />
สำหรับการติดตั้ง หากรันบนคอมพิวเตอร์ทั่วไป ให้ใช้คำสั่ง<br />
<blockquote class="tr_bq">
pip install pennylane pennylane-sf</blockquote>
<h4>
การใช้งาน</h4>
สามารถอ่านเอกสารได้การใช้งานได้ที่ <a href="https://pennylane.readthedocs.io/en/stable/">https://pennylane.readthedocs.io/en/stable/</a><br />
<br />
นอกจากนั้น ทาง PennyLane ได้ทำ Notebook ตัวอย่างการทำ Quantum Machine Learning เช่น Quantum transfer learning สำหรับแยกรูปภาพผึ้งกับมดโดยนำมาประยุกต์กับ ResNet18 อีกด้วย<br />
<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="618" data-original-width="1126" height="350" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg8V6zVJTJ82GQ3XyR5RmokF8_ZSd-n_8qzdfSekG4trmpneP37ERZI_2EMmVKjbFGyTBs2CCkpaRCRulu6M0k5QizXrqGJj0naX7qO165pfLo1Sj56hobZPBLXLBN-ihaICE3lh1T-QfY/s640/Annotation+2020-06-14+205437.jpg" title="ตัวอย่าง Quantum transfer learning สำหรับแยกรูปภาพผึ้งกับมดโดยนำมาประยุกต์กับ ResNet18" width="640" /></div>
<br />
ดูตัวอย่างการทำ Quantum Machine Learning ได้ที่ <a href="https://pennylane.ai/qml/demos/" rel="nofollow" target="_blank">https://pennylane.ai/qml/demos/</a><br />
<br />
หน้าหลักโครงการ PennyLane <a href="https://pennylane.ai/" rel="nofollow" target="_blank">https://pennylane.ai/</a>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-23889130281402004332020-06-13T22:09:00.001+07:002020-06-13T22:25:56.603+07:00ทำ Image Recognition ง่าย ๆ ด้วย detecto<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLW2BXZUu3k3hIq3aKTnvjQKc_lJp3JOMSXfaQxyNyIsuFKwVCwqO4tKRDBgt3gc0AViQ4gOFVcjsTUJVyMEi1-lN-at77Yj88PP06_sJ4mnaNg8OhmPouuF6AI7Zm_d0g5OG44zetids/s1600/apple_orange.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="ตัวอย่างการใช้งานกับรูปภาพ" border="0" data-original-height="618" data-original-width="858" height="230" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLW2BXZUu3k3hIq3aKTnvjQKc_lJp3JOMSXfaQxyNyIsuFKwVCwqO4tKRDBgt3gc0AViQ4gOFVcjsTUJVyMEi1-lN-at77Yj88PP06_sJ4mnaNg8OhmPouuF6AI7Zm_d0g5OG44zetids/s320/apple_orange.png" title="ทำ Image Recognition ง่าย ๆ ด้วย detecto" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">ตัวอย่างการใช้งานกับรูปภาพ ภาพ : <a href="https://github.com/alankbi/detecto" rel="nofollow" target="_blank">https://github.com/alankbi/detecto</a></td></tr>
</tbody></table>
สวัสดีผู้อ่านทุกท่านครับ หลาย ๆ ท่านที่ทำ AI สาย CV คงหนีไม่พันทำระบบจดจำวัตถุหรือ Image Recognition วันนี้เรามีวิธีการทำต่าง ๆ อย่าง Deep Learning ที่เป็นที่นิยมกันในปัจจุบัน แต่การทำระบบจดจำวัตถุในภาพนั้น กลับไม่ง่ายเท่าไร ยิ่งหากต้องทำข้อมูลสำหรับจดจำที่โมเดลปัจจุบันไม่มี หรือ ต้องการใช้เฉพาะด้านจะยิ่งยากขึ้นไปอีก<br />
<br />
วันนี้ผมจะมาแนะนำเครื่องมือทำระบบจดจำวัตถุง่าย ๆ ด้วย detecto กันครับ<br />
<a name='more'></a><br />
detecto เป็นไลบารีสร้างโมเดล computer vision กับ PyTorch สำหรับงาน Image Recognition รองรับ transfer learning กับข้อมูลที่สร้างขึ้นมาใหม่ รองรับรูปภาพและวิดีโอ<br />
<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiOXex7N2q1K6B3OLurrRQCRLNlsq6sZ3Wtb6h0JL9Fw1myX6UB2oeb_7TmD_wy85UZ_Pi814Ru13Hh18VM0xyUwpCD44r_c6ZwrEfh7netwSrFgA39HyjIPOfrevw54oOcVGZkFsC8-g/s1600/demo.gif" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="ตัวอย่างการใช้งานกับวิดีโอ" border="0" data-original-height="373" data-original-width="600" height="198" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiiOXex7N2q1K6B3OLurrRQCRLNlsq6sZ3Wtb6h0JL9Fw1myX6UB2oeb_7TmD_wy85UZ_Pi814Ru13Hh18VM0xyUwpCD44r_c6ZwrEfh7netwSrFgA39HyjIPOfrevw54oOcVGZkFsC8-g/s320/demo.gif" title="" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">ตัวอย่างการใช้งานกับวิดีโอ ภาพ : <a href="https://github.com/alankbi/detecto" rel="nofollow" target="_blank">https://github.com/alankbi/detecto</a></td></tr>
</tbody></table>
และเป็น MIT License อีกด้วย สามารถเอาไปปรับแต่งอะไรได้เลย<br />
<br />
การทำงาน ตัว detecto ใช้โมเดล pre-trained Faster R-CNN ResNet-50 FPN ในการทำงาน<br />
<h3>
<b>การติดตั้ง detecto</b></h3>
ก่อนอื่นให้ติดตั้ง PyTorch ก่อน โดยเข้าไปอ่านวิธีติดตั้ง PyTorch ได้ที่ <a href="https://pytorch.org/" rel="nofollow" target="_blank">pytorch.org</a><br />
<br />
พอติดตั้ง PyTorch เสร็จแล้ว สามารถติดตั้ง detecto ได้ด้วยคำสั่ง<br />
<blockquote class="tr_bq">
pip install detecto</blockquote>
<br />
จากนั้น เรามาลองใช้งานกันดูครับ<br />
หากเรามีภาพ<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhGvGdkHVk_9n6Spwtms0VtiPnjQcbRTQKR9YXZcDeXZzO0DIc_Bo8aM5DX3rXzu5IbMga6SGSFbRkDrGDLSyIPJbzNbkBRZWAbIajU0kLoXf5Z0v8SCMjDy4KrOVvm56dEyofPB7rAfwQ/s1600/an_vision-gDPaDDy6_WE-unsplash.jpg" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" data-original-height="1067" data-original-width="1600" height="213" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhGvGdkHVk_9n6Spwtms0VtiPnjQcbRTQKR9YXZcDeXZzO0DIc_Bo8aM5DX3rXzu5IbMga6SGSFbRkDrGDLSyIPJbzNbkBRZWAbIajU0kLoXf5Z0v8SCMjDy4KrOVvm56dEyofPB7rAfwQ/s320/an_vision-gDPaDDy6_WE-unsplash.jpg" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Photo by <a href="https://unsplash.com/@anvision" rel="nofollow" target="_blank">an_vision</a> on <a href="https://unsplash.com/s/photos/apple?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" rel="nofollow" target="_blank">Unsplash</a></td></tr>
</tbody></table>
เรามาเขียนโค้ดสำหรับ Image Recognition รูปภาพนี้กัน<br />
Google Colab : <a href="https://colab.research.google.com/drive/1q8U1cgzFc8LxDKUBCxInMBoqfHzKV2tV?usp=sharing" rel="nofollow" target="_blank">https://colab.research.google.com/drive/1q8U1cgzFc8LxDKUBCxInMBoqfHzKV2tV?usp=sharing</a><br />
<br />
โค้ด <br />
<pre>from detecto.core import Model
from detecto import utils, visualize
model = Model() # เรียกใช้งานโมเดล
image = utils.read_image('photo-1568702846914-96b305d2aaeb?ixlib=rb-1.2.1') # ดึงข้อมูลไฟล์รูปภาพเข้ามา
labels, boxes, scores = model.predict(image) # รับ labels, พิกเซส และ scores
predictions = model.predict_top(image) # รับเฉพาะ labels ที่มี scores สูงสุด
visualize.show_labeled_image(image, boxes, labels) # โชว์ผลลัพธ์ภาพบน Ipython notebook</pre>
<br />
ผลลัพธ์<br />
<div class="separator" style="clear: both; text-align: center;">
<img border="0" data-original-height="252" data-original-width="372" height="216" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhMvphnChIQ6S9U1XQDi20qzyqSuUd2bZw74KxhMjI87GENWcnteQMGJQPIZpZFe76xxWFM4CCHtDZh_JbEgOu2c2aNyvTXDEbzzmnf78uqQaTb0bbQ4IFlhBGN6f-a5tou5aTySGJdSsw/s320/index.png" width="320" /></div>
นอกจากนั้น ยังรองรับ Image Recognition สำหรับวิดีโอและ live วิดีโออีกด้วย สามารถอ่านเพิ่มเติมได้ที่ <a href="https://detecto.readthedocs.io/en/latest/?badge=latest" rel="nofollow" target="_blank">https://detecto.readthedocs.io/en/latest/?badge=latest</a><br />
<hr />
<br />
ต่อไป เรามาลองสร้างชุดข้อมูลรูปภาพของเราเองเพื่อนำมา transfer learning ด้วย detecto กัน<br />
<br />
<blockquote class="tr_bq">
ขอขอบคุณภาพจาก SpaceX (CC BY-NC) source : <a href="https://www.flickr.com/photos/spacex/" rel="nofollow" target="_blank">https://www.flickr.com/photos/spacex/ </a></blockquote>
<br />
ขั้นตอนแรก เรากำหนดโจทย์ จะทำระบบตรวจจับตำแหน่งจรวดอวกาศ<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<img border="0" data-original-height="285" data-original-width="840" height="135" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgEfjKNbz9isJI-UCCtfaOTmOMUCTu1A3Frv1qTnWqlbJtrs3VqfWiDQJwgGDforX0WcORRNF6_XCbcik6ps8B4roqszi8IkVOz1_N9tfLJ06DII5jjGrV-qZ5RIh4Vimx_s3mXulMK58g/s400/Annotation+2020-06-13+213153.jpg" width="400" /></div>
ขั้นตอนที่สอง หารูปภาพจรวด (ยิ่งมากยิ่งดี) แต่สำหรับบทความนี้ขอเลือกรูปมาแค่บางส่วน ขนาดชุดข้อมูลเล็ก ให้นำภาพทั้งหมดมาอยู่ในโฟลเดอร์ images ที่อยู่ถัดจากโฟลเดอร์ project<br />
<br />
ขั้นตอนที่สาม โหลด labelimg จาก <a href="https://tzutalin.github.io/labelImg/" rel="nofollow" target="_blank">https://tzutalin.github.io/labelImg/</a> มาจะได้หน้าต่างดังนี้<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhxJzutofs9IBU3OJhhSK5U_6CZC_vQFjGt5mA7UxssZan801GnsfFsDqbPrcQklL21Rzi52Zv188RWkbPgOA4SsWfqCdhdezQoNZlzAiRzMG5yCq874-O6EI6qJ2aw85MTe-lB4iXydvo/s1600/Annotation+2020-06-13+213658.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="726" data-original-width="1366" height="340" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhxJzutofs9IBU3OJhhSK5U_6CZC_vQFjGt5mA7UxssZan801GnsfFsDqbPrcQklL21Rzi52Zv188RWkbPgOA4SsWfqCdhdezQoNZlzAiRzMG5yCq874-O6EI6qJ2aw85MTe-lB4iXydvo/s640/Annotation+2020-06-13+213658.jpg" width="640" /></a></div>
หากตรง PascalVOC เป็น yolo ให้คลิกให้เป็น PascalVOC<br />
<div class="separator" style="clear: both; text-align: center;">
<img border="0" data-original-height="69" data-original-width="115" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPtbgnMncXGz2AyEPUrAkorj3nSsYZcGxh81Za7Bb0ESYIQn8iu3I8SP2BPQ6PZv7kQ-2lUbxt3r_r2-UT-v8xbqdRw0PvU7bmeXZEzLSE5IHuM0Qa2GH6YoLyEr2Ap8ZZDfiLZnDbAv0/s1600/Annotation+2020-06-13+213745.jpg" /> คลิกให้เป็น <img border="0" data-original-height="66" data-original-width="101" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4A1TcFzSsJUs79EvspnTNau8fEKT2R-XAj-QUKdqt1TfWvvzbBJil9aQTD6Z5D87Dkml0Uqw5Hd1jcfdX6nEko-f2jk50Ba2QWC8J1NlZqU08RLHAOAzmJkzLhBBTW66Wam67ny2-_jg/s1600/Annotation+2020-06-13+213833.jpg" /></div>
กด Open Dir แล้วเลือก โฟลเดอร์ images ที่เก็บรูปภาพจรวดของเรา<br />
<div class="separator" style="clear: both; text-align: center;">
<img border="0" data-original-height="725" data-original-width="1366" height="339" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi0z090_xr-3FD-iotyun3_hW5uJfdYc5ZMwiTytFn1r_yWdblZhtNoiYLUJD327BtQ5_1QkNjIHfp0na4_dn9JvST8E8RzyIid1sP8DnDUo12Yy52MdGoNxs7pfmIJveS-hLFJZgr5bJo/s640/Annotation+2020-06-13+214047.jpg" width="640" /></div>
ให้คลิก Create\nRectBox แล้วเลือกบริเวณในภาพที่เป็นจรวด<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4RXiJqLIxznAgjBye36hvN-Q15U4O2j0qqh8WrDIIQQ8ldE3rS51nyOo4G6M6gxbBgi-WnWZll7Q7E51H4CMBDVM68_dCylVuOZhjL8lrfSr0PyLMJBaPo34YN9PmI5T7_FoQm9O04V0/s1600/Annotation+2020-06-13+214233.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="330" data-original-width="351" height="300" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj4RXiJqLIxznAgjBye36hvN-Q15U4O2j0qqh8WrDIIQQ8ldE3rS51nyOo4G6M6gxbBgi-WnWZll7Q7E51H4CMBDVM68_dCylVuOZhjL8lrfSr0PyLMJBaPo34YN9PmI5T7_FoQm9O04V0/s320/Annotation+2020-06-13+214233.jpg" width="320" /></a></div>
จากนั้นจะมีช่องให้พิมพ์ label บริเวณรูปภาพที่ต้องการ ในนี้เป็น rocket แล้วกด OK<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<img border="0" data-original-height="97" data-original-width="192" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjZ3Qt1B4CbXTAUXZH6ExJX_sl7WFP5qylcGoiTkYVHgQf1IsQwsPgEa_ZD3V-Ha7oL4QTTO9zA3gooUekUs2aEVIO8_kzy1iZqMC2Hjw4QX-gE7BCtMtYJ6eiPAEeHJMIk-aJ_RfCSxhI/s1600/Annotation+2020-06-13+214330.jpg" /> </div>
<div class="separator" style="clear: both; text-align: center;">
<img border="0" data-original-height="249" data-original-width="88" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhpAWd5DHs4jGGBhEfXmdrbsc5WBP03iPGJhjLkmuV0Si91kER7ZIR5uDQdDpqqDBwDihbmUq2ntmN2d4a1gwNQAPm6AmxYblX1tyZb4ivA-zxrN_xIdpG1O0fMifMzlkieFQ47nLDPHKQ/s1600/Annotation+2020-06-13+214527.jpg" /></div>
จากนั้นกด Save ทำแบบนี้จบครบทุกรูป<br />
<div class="separator" style="clear: both; text-align: center;">
<img border="0" data-original-height="710" data-original-width="1366" height="332" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhhErqKS5WNq3S5C-J3aTTN2xHcn30I5G-e0J9JhHFqGmNZ98RHKZvJldkYqO4TK_L30aBI3OSwrT4AzFZXb9EbzwE_gultev0dg4qX-rqC_wDIkaooRDXyLyP0BIsbD_dSulqNnZZZBf8/s640/Annotation+2020-06-13+214826.jpg" width="640" /></div>
ตอนนี้ในโฟลเดอร์ images จะมีทั้งไฟล์รูปภาพและไฟล์ xml สำหรับนำไปสอนโมเดล<br />
<blockquote class="tr_bq">
project/ <br />
images/<br />
.. รูปภาพ.jpg<br />
.. รูปภาพ.xml</blockquote>
ต่อไปให้สร้างโฟลเดอร์ train_labels กับ val_labels ใน project จะได้<br />
<blockquote class="tr_bq">
project/ <br />
train_labels/<br />
val_labels/<br />
images/ <br />
.. รูปภาพ.jpg<br />
.. รูปภาพ.xml</blockquote>
<br />
แล้วเขียนโค้ดสำหรับแบ่งไฟล์ xml ในโฟลเดอร์ project กัน แล้วรัน<br />
<code>
import glob<br />from shutil import copyfile<br />from sklearn.model_selection import train_test_split<br /><br /><br />path = './images/'<br />files = [f.split('images\\')[-1].replace('.xml','') for f in glob.glob(path + "*.xml", recursive=True)]<br />files.sort()<br />train,val=train_test_split(files, test_size=0.1, random_state=42)<br /><br />for i in files:<br /> copyfile('./images/'+i+'.xml','./train_labels/'+i+'.xml')<br /><br />for i in val:<br /> copyfile('./images/'+i+'.xml','./val_labels/'+i+'.xml')</code><br />
จากนั้น ไปขั้นตอนต่อไปกัน<br />
<br />
ขั้นตอนที่สี่ ฝึกสอนโมเดล โดยใช้โค้ดดังนี้<br />
<code>
from detecto import core, utils<br />from torchvision import transforms<br />import matplotlib.pyplot as plt<br /><br /># Convert XML files to CSV format<br />utils.xml_to_csv('train_labels/', 'train_labels.csv')<br />utils.xml_to_csv('val_labels/', 'val_labels.csv')<br /><br /># Define custom transforms to apply to your dataset<br />custom_transforms = transforms.Compose([<br /> transforms.ToPILImage(),<br /> transforms.Resize(800),<br /> transforms.ColorJitter(saturation=0.3),<br /> transforms.ToTensor(),<br /> utils.normalize_transform(),<br />])<br /><br /># Pass in a CSV file instead of XML files for faster Dataset initialization speeds<br />dataset = core.Dataset('train_labels.csv', 'images/', transform=custom_transforms)<br />val_dataset = core.Dataset('val_labels.csv', 'val_images') # Validation dataset for training<br /><br /># Create your own DataLoader with custom options<br />loader = core.DataLoader(dataset, batch_size=2, shuffle=True) <br /><br />model = core.Model(['rocket'])<br />losses = model.fit(loader, val_dataset, epochs=5, learning_rate=0.001, verbose=True)<br /><br />plt.plot(losses) # Visualize loss throughout training<br />plt.show()<br /><br />model.save('model_weights.pth') # Save model to a file<br /><br /># Directly access underlying torchvision model for even more control<br />torch_model = model.get_internal_model()<br />print(type(torch_model))</code><br />
เพียงเท่านี้เราก็ได้โมเดล Image Recognition ตรวจจับจรวดอวกาศแล้ว ส่วนเวลาเรียกใช้งานเพียงแค่ใช้คำสั่ง<br />
<code>
from detecto.core import Model<br />from detecto import utils, visualize<br /><br />
labels = ['rocket'] # อย่าลืมพิมพ์ label ที่เราสร้าง<br />
model = Model.load('model_weights.pth', labels)<br /><br />image = utils.read_image('photo-rocket.jpg') # ดึงข้อมูลไฟล์รูปภาพเข้ามา<br /><br />labels, boxes, scores = model.predict(image) # รับ labels, พิกเซส และ scores<br />predictions = model.predict_top(image) # รับเฉพาะ labels ที่มี scores สูงสุด<br /><br />visualize.show_labeled_image(image, boxes, labels) # โชว์ผลลัพธ์ภาพบน Ipython notebook </code><br />
<br />
<br />
อ่านเอกสารเพิ่มเติมได้ที่ <a href="https://detecto.readthedocs.io/" rel="nofollow" target="_blank">https://detecto.readthedocs.io</a><br />
GitHub : <a href="https://github.com/alankbi/detecto" rel="nofollow" target="_blank">https://github.com/alankbi/detecto </a>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com3tag:blogger.com,1999:blog-2940971822351202057.post-19166345937404903312020-05-25T13:38:00.000+07:002020-05-25T13:38:03.755+07:00Pyodide: รัน Python บน Web Browser ด้วย WebAssembly 🐍<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="729" data-original-width="1366" height="340" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi3GN8tMe5QlkUaNJXnvlWK9fci4N599j63GH2MznOZFEM6wV_OYvr_47qKSNOok-u4Pn1gujTB7By6GtOdeGV8mdslMtj45JxrUYa1vEOvIAo75CuDK4SupoklRqJOeLGmt7CNcqduFLg/s640/n.jpg" title="Pyodide : รัน Python บน Web Browser ด้วย WebAssembly" width="640" /></div>
<br />
ปัจจุบัน ต้องยอมรับว่ากระแส WebAssembly มาแรงจริง ๆ หลายภาษาสามารถโยกย้ายไปรันบน WebAssembly ได้ รวมถึงภาษา Python ด้วย<br />
<a name='more'></a><br />
<br />
Pyodide เป็นโครงการที่แปลง Python runtime ให้สามารถทำงานบน Web Browser ได้ด้วย WebAssembly พัฒนาโดย Mozilla โดยรวบรวมไลบรารีอย่าง NumPy, Pandas, Matplotlib, NetworkX และไลบรารีอื่น ๆ กว่า 30 ไลบรารีอีกด้วย นอกจากนั้นยังมีจุดเด่น คือ สามารถติดตั้งไลบรารีเสริมจาก PyPI ได้อีกด้วย (ดีกว่าที่คาดไว้) แต่รองรับเฉพาะไลบรารีที่เป็น pure Python เท่านั้น <br />
<br />
<h3>
การใช้งานเบื้องต้น</h3>
เราสามารถเรียกใช้งาน Pyodide โดยดึงผ่าน CDN ที่เตรียมไว้มารันกับ javascript ได้ทันที<br />
<blockquote class="tr_bq">
https://pyodide-cdn2.iodide.io/v0.15.0/full/pyodide.js</blockquote>
ตัวอย่างโค้ดจากเอกสาร <a href="https://pyodide.readthedocs.io/en/latest/using_pyodide_from_javascript.html" rel="nofollow" target="_blank">Using Pyodide from Javascript</a><br />
<code><!DOCTYPE html><br /><html><br /><head><br /> <script type="text/javascript"><br /> // set the pyodide files URL (packages.json, pyodide.asm.data etc)<br /> window.languagePluginUrl = 'https://pyodide-cdn2.iodide.io/v0.15.0/full/';<br /> </script><br /> <script src="https://pyodide-cdn2.iodide.io/v0.15.0/full/pyodide.js"></script><br /></head><br /><body><br /> Pyodide test page <br><br /> Open your browser console to see pyodide output<br /> <script type="text/javascript"><br /> languagePluginLoader.then(function () {<br /> console.log(pyodide.runPython('import sys\nsys.version'));<br /> console.log(pyodide.runPython('print(1 + 2)'));<br /> });<br /> </script><br /></body> </code><br />
<br />
เอาลอง เรามาลองเล่น Pyodide ผ่านหน้า Pyodide terminal emulator 🐍 กัน<br />
<br />
เข้าไปที่ <a href="https://pyodide-cdn2.iodide.io/v0.15.0/full/console.html" rel="nofollow" target="_blank">https://pyodide-cdn2.iodide.io/v0.15.0/full/console.html</a> เราสามารถเรียกใช้คำสั่ง python พื้นฐานได้เกือบทั้งหมด น่าจะเพียงพอต่อการรันโค้ดพื้นฐาน<br />
<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="652" data-original-width="1151" height="362" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgWmaHlQBKJ4kjYKHXEXqZkUtY7jDUBC0f-v_of7Umx3VUKFxMNiSOGCqLJYf4_8GXwIJwMRP4Hx2CvZx2pv43qob7fzR-llSfq7QdGyDAC2Y4jO4h3EKRPB-bpIkRas5HLrD0aDyxEO6s/s640/n1.jpg" title="Pyodide สามารถรันโค้ด Python ได้แบบสบาย ๆ บน Web Browser ผ่าน WebAssembly" width="640" /></div>
จะเห็นได้ว่า Pyodide สามารถรันโค้ด Python ได้แบบสบาย ๆ บน Web Browser ผ่าน WebAssembly ไม่รู้สึกถึงความช้ามากนัก<br />
<br />
ต่อไปเรามาลองติดตั้งไลบรารีจาก pypi ลง Pyodide กัน โดยใช้คำสั่ง<br />
<blockquote class="tr_bq">
import micropip<br />
micropip.install('ชื่อไลบรารีหรือลิงก์ไฟล์ whl')</blockquote>
<h3>
ตัดคำ PyThaiNLP บน Web Browser </h3>
เรามาลองไลบรารีตัวจริงอย่าง PyThaiNLP เพื่อตัดคำภาษาไทยกัน<br />
<pre>import micropip
micropip.install('pythainlp')</pre>
<br />
ผลลัพธ์<br />
<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="203" data-original-width="920" height="140" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgARLdi74IRE-Y4SOkkIPzZXU3V1sfrfyKFagW2gZhPTgBAZvRVOm3kK6aYANM_psGHTle8e6iDgwdu4Sw-c88m9dAxHQfUv4O4ToxJZWnDVd_2c2xKhxUspbxhas6RnfcvaghNYe5NkkU/s640/n2.jpg" title="Pyodide ติดตั้งไลบรารีจาก pypi ที่ไม่ใช่ pure Python ไม่ได้" width="640" /></div>
จะพบว่าการติดตั้ง PyThaiNLP ลง Pyodide แบบนี้จะมีปัญหาเพราะมีบางไลบรารีที่ pythainlp ใช้ ไม่ได้เป็น pure Python เหตุนี้ Pyodide ติดตั้งไลบรารีจาก pypi ที่ไม่ใช่ pure Python ไม่ได้ แต่ปัญหานี้ถูกแก้ไขไปแล้วใน PyThaiNLP 2.2 ที่กำลังพัฒนา สามารถติดตั้งได้โดยใช้โค้ดดังนี้<br />
<pre>import micropip
micropip.install('tinydb')
micropip.install('requests')
micropip.install('https://files.pythonhosted.org/packages/3a/b3/4127905c4f7457abb018a0f4cb26130a59f937b3a1925cb0d171c18ab153/pythainlp-2.2.0.dev1-py3-none-any.whl')</pre>
<br />
<b>ผลลัพธ์</b><br />
<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="421" data-original-width="1347" height="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjOPto7M78GAtmzgvSc37eGfHRnPNJFImi-yovo77NVT27bKV6s2nAR9Zq1q2MpuO6ErcxL6DuxR3fgrb4CttMQmd3lzudcAH-KtmY1e2_oWRd0pRe1VT7Xxv9r4Wy7dk-kaxitpqUVOZ0/s640/n3.jpg" title="ถ้าขึ้น Installed ถือว่าติดตั้ง PyThaiNLP สำเร็จ" width="640" /></div>
ถ้าขึ้น Installed ถือว่าติดตั้งสำเร็จ ต่อไปเรามาลองตัดคำภาษาไทยด้วย PyThaiNLP ผ่าน Browser ด้วย WebAssembly กัน<br />
<pre>from pythainlp.tokenize import word_tokenize
text = "เรามาลองทดสอบอะไรเล่นกัน"
word_tokenize(text)</pre>
<br />
<b>ผลลัพธ์</b><br />
<div class="separator" style="clear: both; text-align: center;">
<img border="0" data-original-height="259" data-original-width="980" height="168" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgXYFfaeSJLhy7uaeuuFK_um6cuoZvKuX-aUDRkO8DVZGAveS9Y5gNQV0k2iu4_UJwF5HkBIZ4VvtQDG9NmWkJzyUwL3zPq2JZubqEuH6GmaKMaxrlwsDdqLlblA1Kc0NfwtdajtUTR7pU/s640/n4.jpg" width="640" /></div>
<h3>
รัน NumPy บน Web Browser</h3>
<span>เราสามารถเรียกใช้งาน NumPy จาก Pyodide ได้ทันทีโดยไม่ต้องติดตั้งเอง ใช้คำสั่ง</span><br />
<blockquote class="tr_bq">
<span>pyodide.loadPackage(['numpy'])</span></blockquote>
<span>ทดสอบการใช้งาน</span><br />
<blockquote class="tr_bq">
<span><span data-text=">>> " style="--color: red; color: red;"></span><span>import numpy as np</span></span><br />
<span><span><span>np.array([1, 2, 3, 4, 5])</span></span></span><br />
<span><span><span><span>print(np.__version__)</span></span></span></span></blockquote>
<b><span><span><span><span>ผลลัพธ์</span></span></span></span></b><br />
<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="423" data-original-width="830" height="326" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiL2IjgnAXNlR_GwPaf2G37rWA4EL-09JYILqULgkzr1TNkFoT-Nnu9h_HSCSAk4ZvzJa4viYOMNWEZfRdtATkWssPJ6a9FV4uAi_y-n6DYohzIsS1w-d8gagp4NFHR_ita1PoA61tqlVg/s640/n5.jpg" title="รัน NumPy บน Web Browser" width="640" /></div>
<span><span><span><span> </span> </span></span></span><br />
<span><span><span>นอกจากนั้น สามารถเข้าไปดูไลบรารีที่ Pyodide รองรับได้ที่ <a href="https://github.com/iodide-project/pyodide/tree/master/packages" rel="nofollow" target="_blank">https://github.com/iodide-project/pyodide/tree/master/packages</a></span></span></span><br />
<br />
<span><span><span>อ่านเอกสารการใช้งาน Pyodide ได้ที่ <a href="https://github.com/iodide-project/pyodide" rel="nofollow" target="_blank">https://github.com/iodide-project/pyodide</a></span></span> </span>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-1531304023699999062020-04-27T17:29:00.001+07:002020-04-27T17:29:26.547+07:00รู้จักกับ PyPI<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="185" data-original-width="247" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgKI_QNGFQIiTPts5EBZV1VG5UkXGO-meVboqmMXHByvMtlgMHRvrX6kV4vxFs0nEAmxNAJPLAiJ75h7pytQtpBY5Wb0qXm6v6gS4e96Y1DOCR_4t0yXD5glKVApC1Hsh4V_Y1DrGv7Juo/s1600/logo-large_72ad8bf1.png" title="รู้จักกับ PyPI" /></div>
<br />
PyPI ย่อมาจาก Python Package Index เป็นแหล่งรวมชุดคำสั่งของภาษา Python โดยทำงานร่วมกับคำสั่ง pip สำหรับติดตั้งชุดคำสั่งใน Python<br />
<a name='more'></a><br />
<br />
ผู้ใช้งานสามารถค้นหาไลบรารีหรือโปรแกรมภาษา Python ได้ง่าย ๆ จากช่องค้นหา และมีรายละเอียดการคำสั่งติดตั้ง กับประวัติรุ่นไลบรารีที่ต้องการ<br />
<br />
ส่วนสำหรับนักพัฒนาจะนำชุดคำสั่งภาษา Python ที่เขียน ไม่ว่าจะเป็นไลบรารีหรือโปรแกรมต่าง ๆ ที่ใช้ร่วมกับภาษา Python ขึ้นไปฝากไว้กับ PyPI โดย PyPI มีอยู่ 2 ส่วนด้วยกัน<br />
1. Test PyPI<br />
<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="624" data-original-width="1349" height="185" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjwK-8gEs1pjDL01orFeEnzlXuIWsd2x9bWY0nwgrvcqxyq-0pqo4TeogWffxzJ9ZK3YbcqZWASJdwY06_HFUvyZbw3wvHzgYqS0rPONPPL0xskl0gc2lrZiEOhMkiwZOsDdkcIgWEOD8k/s400/testpypi.png" title="Test PyPI" width="400" /></div>
Test PyPI ตั้งอยู่ที่ <a href="https://test.pypi.org/" rel="nofollow" target="_blank">https://test.pypi.org/</a> ให้นักพัฒนาสามารถอัพโหลดไลบรารีหรือโปรแกรมภาษา Python ของตัวเองขึ้นทดสอบก่อนนำไปอัพโหลดขึ้น PyPI โดยการติดตั้งไลบรารีจาก Test PyPI จะใช้คำสั่งที่ยาวขึ้นมาหน่อยดังนี้<br />
<blockquote class="tr_bq">
pip install -i https://test.pypi.org/simple/ ชื่อไลบรารี</blockquote>
2. PyPI<br />
<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="542" data-original-width="1346" height="160" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvzzPZVN1Ax7_vmqLDLygvkrfS1SutclAZMNjmfsuxQPS8bVcTsLpZkTvljh9wV84p8jcXMCBfZPwd9-Xlf20j8qK54NCncXuZmsaipwUGxP7nWR-kuN0P_U-RvI4u5AFszqgut5EZbDY/s400/pypi.png" title="PyPI" width="400" /></div>
PyPI ตั้งอยู่ที่ <a href="https://pypi.org/" rel="nofollow" target="_blank">https://pypi.org/</a> ผู้ใช้งานสามารถติดตั้งไลบรารีหรือโปรแกรมโปรแกรมภาษา Python ได้ หากว่านักพัฒนาอัพโหลดไลบรารีหรือโปรแกรมของตัวเองขึ้น PyPI แล้ว เพียงแค่ใช้คำสั่ง<br />
<blockquote class="tr_bq">
pip install ไลบรารี</blockquote>
<br />
นอกจากนั้น PyPI ยังมี API ให้ดึงไปใช้งานอีกด้วย สามารถอ่านรายละเอียดได้ที่ <a href="https://warehouse.readthedocs.io/api-reference/" rel="nofollow" target="_blank">https://warehouse.readthedocs.io/api-reference/</a>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-15358857720337477262020-04-26T14:55:00.000+07:002020-07-19T17:20:33.309+07:00ฝึกเขียนโปรแกรมภาษา Python แบบ Block ด้วย BlockPy<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="384" data-original-width="798" height="306" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgf_t4r9goNsad56pIXgQvWnh-Qiz-FLs7Si6uxc8JkTnKrPnrfSkxAbjnIBIwf5E2VmTPANmonByhSlveAEX3W5rzLCe_2TQt1rO2lV2cX8Hmvb63iBaQR-kfUM0CUkiBKoGLLLdEP6qA/s640/Annotation+2020-04-26+135422.png" title="ฝึกเขียนโปรแกรมภาษา Python แบบ Block ด้วย BlockPy" width="640" /></div>
<br />
วันนี้เราจะมาฝึกเขียนโปรแกรมภาษา Python แบบ Box ด้วย BlockPy กันครับ<br />
<a name='more'></a>BlockPy เป็นเครื่องมือสำหรับเขียนโปรแกรมภาษา Python แบบ Block , ข้อความ หรือทั้งคู่ ออกแบบสำหรับ Data Science และนักเรียน โดยเป็นซอฟต์แวร์โอเพนซอร์ซ (Open source software) เป็น Online Coding Environment สามารถใช้งานได้ทันทีไม่ต้องลงโปรแกรม มีเครื่องมือสำหรับช่วยวาดกราฟรวมถึงเขียนเต่า turtle อีกด้วย <br />
<div style="text-align: center;">
<br />
<iframe allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/0Q92VJMlf_0" width="560"></iframe> </div>
<br />
การใช้งาน เปิดเว็บบราวเซอร์ เข้าไปที่ <a href="https://think.cs.vt.edu/blockpy/" rel="nofollow" target="_blank">https://think.cs.vt.edu/blockpy/</a><br />
<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="602" data-original-width="1330" height="288" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjH2GBlR6yVduItJQPShQc2jCkkU-RUTP3X8SyR3XClGn6KWt8LCAnocNLWCdZhkXvVOxirRHXi3a84aBE-1B6D73gpBBTC7kh3-lbVSxptu-i5vJhlBqW50D0rvOqHTfelJG0pPrlI7i4/s640/Annotation+2020-04-26+131715.png" title="หน้าหลัก BlockPy" width="640" /></div>
แล้วคลิก Try Editor บนแถบเมนูข้างบน จะพบกับหน้า BlockPy: Scratch Canvas<br />
<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="1101" data-original-width="1349" height="522" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwXNP9SJBzHtW_mqIwJuACcOzoD9aDuWZ0-VNmrWVnTA1E2PCI8rt07KOIu5VKjMk167GuKdGxnGUu7gUoa7MF_NR5K6oOlDMgJSS5e3jpIfM_Sa-4gWHIkfVMmhyphenhyphenPDPkp8gt3ab3Kscc/s640/Screenshot_2020-04-26+BlockPy.png" title="หน้า BlockPy: Scratch Canvas" width="640" /> </div>
<div class="separator" style="clear: both; text-align: left;">
หน้านี้จะมีด้วยกัน 6 ส่วนดังนี้</div>
<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="1101" data-original-width="1349" height="522" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhTouXb0FWsoVY4C0Z-6P1AfV4OyInCN6ZMzGogbQOQa1UYj0DSfvqnZIk8ZxplxvkXTb3BIiQxbKYDsQAuR0KH_Xs_NEN4mRRPUBcTgAwKuPB-v3DURNfJO4WMLZly-jdbAUrBRVawnFM/s640/Screenshot_2020-04-26+BlockPy.png" title="หน้า Editor สำหรับฝึกเขียนโปรแกรมภาษา Python แบบ Block ด้วย BlockPy" width="640" /> </div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
คำอธิบาย</div>
<ol>
<li>แถบเมนู สามารถมาหน้า Editor สมัครสมาชิกและเข้าสู่ระบบได้</li>
<li>แถบ Console ใช้แสดงผลลัพธ์และรับข้อมูลจากแป้นพิมพ์</li>
<li>แถบ Feedback ใช้แสดงหน้าจอข้อผิดพลาดของโปรแกรม</li>
<li>แถบควบคุม สำหรับใช้รัน/หยุดโค้ด, เปลี่ยนโหมดการเขียนโปรแกรม, นำเข้าชุดข้อมูล, อัพโหลดไฟล์ และประวัติการรัน</li>
<li>แถบ Blocks สำหรับใช้เขียนโปรแกรมภาษา Python แบบลากวาง</li>
<li>แถบ Text เขียนโปรแกรม Python แบบใช้ข้อความ</li>
</ol>
<h3 class="separator" style="clear: both; text-align: left;">
<b>การใช้งานเขียนโปรแกรมภาษา Python แบบ Block ด้วย BlockPy เบื้องต้น</b></h3>
<h4 class="separator" style="clear: both; text-align: left;">
<u>โปรแกรมเครื่องบวกเลขง่าย ๆ</u></h4>
<div class="separator" style="clear: both; text-align: left;">
โหมด Blocks (วิดีโอไม่มีเสียง)</div>
<div class="separator" style="clear: both; text-align: left;">
</div>
<div style="height: 0; padding-bottom: 56.25%; position: relative;">
<iframe allowfullscreen="" frameborder="0" mozallowfullscreen="" src="https://www.loom.com/embed/6b24d13067ac466d92c11924c054fa92" style="height: 100%; left: 0; position: absolute; top: 0; width: 100%;" webkitallowfullscreen=""></iframe></div>
<br />
โหมด Text<br />
<code>num1 = int(input('number 1'))<br />
num2 = int(input('number 2'))<br />
sum = num1 + num2<br />
print(sum)</code><br />
<br />
<h4>
เขียนโปรแกรม Python ด้วย turtle</h4>
นอกจากเขียนโปรแกรม Python แบบ Block เหมือนโปรแกรมอื่น ๆ BlockPy ยังรองรับการเขียนโปรแกรมด้วยเต่า turtle บน Python อีกด้วย โดยเราจะยกตัวอย่างการเขียนโปรแกรม turtle วาดรูปสี่เหลี่ยมจัตุรัสบน Python แบบ Block ด้วย BlockPy ได้ดังนี้ (วิดีโอไม่มีเสียง)<br />
<div style="height: 0; padding-bottom: 56.25%; position: relative;">
<iframe allowfullscreen="" frameborder="0" mozallowfullscreen="" src="https://www.loom.com/embed/59cfdd2ee6804032a96674f60752839e" style="height: 100%; left: 0; position: absolute; top: 0; width: 100%;" webkitallowfullscreen=""></iframe></div>
<br />
<h4>
เขียนโปรแกรม Python แสดงกราฟอุณหภูมิเฉลี่ยรายสัปดาห์ของ Aberdeen, SD</h4>
BlockPy สามารถสร้างกราฟสำหรับ Data Science จากข้อมูลได้ โดยมีข้อเสียรองรับกราฟแค่ไม่กี่แบบ เช่น line, scatter, Histogram เท่านั้น และ BlockPy ยังรวมชุดข้อมูล (Dataset) พร้อมใช้งานสำหรับฝึกทำ Data Science โดยสามารถอ่านรายละเอียดได้ที่ <a href="https://corgis-edu.github.io/corgis/blockpy/" rel="nofollow" target="_blank">https://corgis-edu.github.io/corgis/blockpy/</a><br />
<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="607" data-original-width="1343" height="288" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhrw_GvdxhYQDASL45wlFxfUndp2wbtdLaBdah_3U-9ObDZ9jWDyDlzM3KOAvAomy-3P8Znc0oKcCw7VfMw8LXs12iZbwDPAjZUGhYIZmmBDsx-MKUgcEME1D1_TCGtvEu4IXk7sve0C-E/s640/blockpy-dataset.png" title="หน้า BlockPy Dataset รวมชุดข้อมูลต่าง ๆ" width="640" /></div>
สำหรับบทความนี้จะขอเลือกใช้งาน Weather จาก CORGIS Dataset Project เก็บบันทึกข้อมูลสภาพอากาศปี 2016 ที่สหรัฐอเมริกา โดยเลือก Aberdeen, SD (อ่านรายละเอียด Weather ได้ที่ <a href="https://corgis-edu.github.io/corgis/blockpy/weather/" rel="nofollow" target="_blank">https://corgis-edu.github.io/corgis/blockpy/weather/</a>)<br />
<br />
เขียนโปรแกรม Python แสดงกราฟอุณหภูมิเฉลี่ยรายสัปดาห์ของ Aberdeen, SD บน BlockPy ได้ดังนี้ (วิดีโอไม่มีเสียง)<br />
<div style="height: 0; padding-bottom: 56.25%; position: relative;">
<iframe allowfullscreen="" frameborder="0" mozallowfullscreen="" src="https://www.loom.com/embed/8c35f2da242b4a43ac0fb7cb4db059fa" style="height: 100%; left: 0; position: absolute; top: 0; width: 100%;" webkitallowfullscreen=""></iframe></div>
โค้ดแบบ Text<br />
<code>import weather<br />import matplotlib.pyplot as plt<br /><br />y = weather.get('Data.Temperature.Avg Temp','Station.Location','Aberdeen, SD')<br />x = []<br />for i in range(1, len(y) + 1):<br /> x.append(i)<br />plt.title('Temperature Avg Temp of Aberdeen, SD')<br />plt.xlabel('week')<br />plt.ylabel('°F')<br />plt.scatter(x, y)<br />plt.show()
</code><br />
<br />
นอกจากนั้น BlockPy ยังมี courses เรียนออนไลน์แบบฟรี ที่ <a href="https://canvas.instructure.com/courses/1134562" rel="nofollow" target="_blank">https://canvas.instructure.com/courses/1134562</a><br />
ติดตามบทความต่อไปนะครับ<br />
ขอบคุณครับ wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-85957695153243569972020-04-12T17:06:00.000+07:002020-07-18T23:30:12.447+07:00Machine Translation : การแปลภาษาอังกฤษเป็นภาษาไทยด้วยกฎ<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="300" data-original-width="300" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgLvyle8Mq4zdsTO04XvqUcGtcC_OAY9tsxIdAZ6NmQG9QAeD-pmHJue70tnnktcX6m_j5qlFFypgqYOyvp54MsNbU-F7hHzsKT43g-2Ou3bHENgDVSE64IIHRGp6F0VseUo9luGWMbXmw/s1600/mt.png" title="Machine Translation : การแปลภาษาอังกฤษเป็นภาษาไทยด้วยกฎ" /></div>
บทความนี้เรามาลองเขียนโปรแกมภาษา Python โดยเราจะมาเขียนโปรแกรมการแปลภาษาอังกฤษเป็นภาษาไทยด้วยกฎ หรือ English-Thai Rule-based machine translation<br />
<a name='more'></a>เครื่องแปลภาษา (Machine Translation) คือ โปรแกรม หรือ เครื่องแปลภาษา เป็นส่วนหนึ่งของงานด้านการประมวลผลภาษาธรรมชาติ (Natural Language Processing) เป็นงานที่ท้าทายข้อจำกัดทางด้านภาษาของมนุษย์ เพื่อให้ผู้คนสามารถติดต่อสื่อสารกันได้โดยไม่มีกำแพงทางภาษามาขวางกั้นไว้<br />
<br />
เครื่องแปลภาษา เริ่มต้นโดยใช้ความรู้ทางด้านภาษาศาสตร์มาประยุกต์กับทางคอมพิวเตอร์เขียนกฎสำหรับแปลภาษาในคอมพิวเตอร์ เรียกการแปลแบบนี้ว่า Rule-based machine translation (RBMT) ซึ่งพอเวลาผ่านไปสักระยะผู้คนเริ่มเห็นข้อจำกัดการแปลด้วยเทคนิคด้วยกฎ เพราะภาษามนุษย์มีไวยากรณ์มากมายและยากที่จะเขียนให้ครอบคลุม ต่อมาจึงมีเทคนิค Statistical machine translation (SMT) แปลด้วยสถิติ และล่าสุดเป็น Neural machine translation (NMT) ที่ใช้เทคนิคการเรียนรู้เชิงลึก (Deep learning) สามารถแปลได้แม่นยำที่สุดในปัจจุบัน<br />
<br />
เพื่อให้เข้าใจ Rule-based machine translation (RBMT) มากยิ่งขึ้น เรามาลองเขียนโปรแกรมแปลภาษาอังกฤษเป็นภาษาไทยด้วยกฎ หรือ English-Thai Rule-based machine translation กัน<br />
<br />
เนื่องจากเราจะเขียนขึ้นมาใหม่ ไม่อิงเอกสารด้านนี้ที่เคยใช้งานมา และ ใช้เครื่องมือในปัจจุบันช่วยทำโปรแกรมแปลภาษาอังกฤษเป็นภาษาไทยด้วยกฎ<br />
<b><br /></b>
<b>สิ่งที่ต้องเตรียม</b><br />
<ul>
<li>พจนานุกรมคำศัพท์ภาษาอังกฤษ - ภาษาไทย เราใช้พจนานุกรมอิเล็กทรอนิกส์ไทย - อังกฤษ LEXiTRON จากบทความ <a href="https://python3.wannaphong.com/2014/08/dictionary-python-3.html" target="_blank">เขียนโปรแกรมแปลภาษา dictionary บน Python 3</a></li>
</ul>
<b>การทำงาน</b><br />
<ul>
<li>รับประโยคภาษาอังกฤษ 1 ประโยคเข้ามา</li>
<li>ตัดประโยคภาษาอังกฤษ</li>
<li>นำคำไปผ่าน Stemmer ให้เรียบร้อย</li>
<li>นำประโยคที่ผ่านการตัดคำไปหาชนิดของคำ (part of speech)</li>
<li>นำแต่ละคู่คำกับชนิดของคำ ไปค้นคำแปลจากพจานานุกรมภาษาอังกฤษ -> ภาษาไทย ให้ได้คู่คำแปลพร้อมกับชนิดของคำ</li>
<li>นำคู่คำแปลพร้อมกับชนิดของคำ มาจัดเรียงจากไวยากรณ์ภาษาอังกฤษให้เป็นภาษาไทย</li>
<li>นำคำแปลที่ผ่านการจัดเรียงมาแสดงผลจะได้คำแปล</li>
</ul>
<b>เครื่องมือที่เราจะใช้ในการเขียนโปรแกรมแปลภาษาอังกฤษเป็นภาษาไทยด้วยกฎในภาษาไพทอน Python</b><br />
<ul>
<li>NLTK - ใช้ตัดคำภาษาอังกฤษ, Stemmer และชนิดของคำ</li>
<li>sqlite3 - ใช้สำหรับเชื่อมต่อกับพจนานุกรมคำศัพท์ภาษาอังกฤษ - ภาษาไทย</li>
</ul>
มาลงมือเขียนโปรแกรมกัน ก่อนใช้งานให้โหลดชุดข้อมูลของ NLTK ก่อนใช้งานดังนี้<br />
<code>import nltk<br />nltk.download('averaged_perceptron_tagger')<br />nltk.download('universal_tagset')<br />nltk.download('punkt')<br />nltk.download('stopwords')<br />nltk.download('wordnet')</code><br />
<br />
<h3>
ส่วนที่ 1 แปลภาษาแบบคำต่อคำตามชนิดของคำ <u><br /></u></h3>
<u>ค้นคำแปลจากคำศัพท์และตามชนิดของคำ</u><br />
<br />
อย่างแรก เขียนฟังก์ชันค้นหาคำจากฐานข้อมูลพจนานุกรมคำศัพท์ภาษาอังกฤษ - ภาษาไทย ซึ่งเป็นฐานข้อมูล SQLite<br />
<br />
ในไฟล์ lexitron.db จะมี TABLE ชื่อ eng2thai ประกอบไปด้วย id, esearch, eentry, tentry,ecat,ethai,esyn และ eant เราจะค้นทั้งคำศัพท์และตามชนิดของคำ เราจึงต้องค้นจาก esearch กับ ecat<br />
<br />
โดยเขียนเป็นฟังก์ชันสำหรับค้น ชื่อ word2thai ได้ดังนี้<br />
<pre>import sqlite3
conn = sqlite3.connect('lexitron.db')
c = conn.cursor()
def word2thai(word:str,tag:str)->str:
word = word.lower()
if tag == '':
find = c.execute("SELECT * FROM eng2thai WHERE esearch='%s'" % (word))
else:
find = c.execute("SELECT * FROM eng2thai WHERE esearch='%s' and ecat='%s'" % (word,tag))
for row in find:
if '(' not in row[3] and 'คำ' not in row[3]:
return row[3]</pre>
<u>ฟังก์ชันสำหรับทำ Stemmer</u><br />
เราใช้ NLTK ในการทำ Stemmer โดยเราเขียนฟังก์ชันชื่อ prepro ไว้<br />
<pre>from nltk.stem.porter import PorterStemmer
stemmer = PorterStemmer()
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
from nltk.corpus import stopwords
st = stopwords.words('english')
from nltk.stem.snowball import SnowballStemmer
snowBallStemmer = SnowballStemmer("english", ignore_stopwords=True)
from nltk.stem.lancaster import *
lancasterStemmer = LancasterStemmer()
def prepro(listword:list)->list:
temp= [stemmer.stem(i) for i in listword]
sn = [snowBallStemmer.stem(word) for word in temp]
la = [lancasterStemmer.stem(i) for i in sn]
return [i for i in listword]</pre>
<br />
ต่อไปเรามาเขียนฟังก์ชันสำหรับแปลคำกับชนิดคำ ภาษาอังกฤษเป็นภาษาไทยกัน<br />
<u>แปลคำตามชนิดคำจากภาษาอังกฤษเป็นภาษาไทย</u><br />
สมมติ เรามีประโยค<br />
<blockquote class="tr_bq">
sent = "I love you."</blockquote>
เราเอามาแปลงเป็นตัวพิมพ์เล็กทั้งหมด<br />
<blockquote class="tr_bq">
sent = sent.lower()</blockquote>
จากนั้นนำมาตัดคำด้วยคำสั่ง<br />
<blockquote class="tr_bq">
import nltk<br />
token = nltk.word_tokenize(sent)</blockquote>
แล้วนำมาหา part of speech โดยเราจะใช้ Universal Part-of-Speech Tagset เพื่อให้ง่ายต่อการเทียบ part of speech ในการหาคำแปลตามชนิดของคำจากฐานข้อมูลพจนานุกรมคำศัพท์ภาษาอังกฤษ - ภาษาไทย<br />
<blockquote class="tr_bq">
tag = pos_tag(token,tagset='universal')</blockquote>
เนื่องจาก part of speech ของ Universal Part-of-Speech Tagset กับ LEXiTRON มีค่าไม่ตรงกัน เราจึงต้องเขียนตัวแปลจาก part of speech ของ Universal Part-of-Speech Tagset ให้เป็น part of speech ของ LEXiTRON เพื่อให้เวลาค้นหาคำ เจอคำแปลที่ตรงกับไวยากรณ์ที่เขียน<br />
<br />
เราสร้าง DICT สำหรับเทียบ part of speech ของ Universal Part-of-Speech Tagset กับ part of speech ของ LEXiTRON ขึ้นมา<br />
<code>tag2lexitron = {<br />
"ADJ" : "ADJ",<br />
"ADP" : "PREP",<br />
"ADV" : "ADV",<br />
"AUX" : "AUX",<br />
"CCONJ" : "CONJ",<br />
"DET" : "DET",<br />
"INTJ" : "INT",<br />
"NOUN" : "N",<br />
"NUM" : "",<br />
"PART" : "",<br />
"PRON" : "PRON",<br />
"PROPN" : "",<br />
"PUNCT" : "",<br />
"SCONJ" : "CONJ",<br />
"SYM" : "",<br />
"VERB" : "VERB", # VT VI<br />
"X" : "",<br />
"." : "",<br />
"CONJ" : "CONJ",<br />
"PRT":"PREP"<br />
}</code><br />
จากนั้น เขียนฟังก์ชันแปลกัน<br />
<code>def translate(sent:str)->list: <br /> sent = sent.lower()<br /> token = nltk.word_tokenize(sent)<br /> tag = [(i[0],tag2lexitron[i[1]]) for i in nltk.pos_tag(token,tagset='universal')]<br /> thai = [word2thai(i[0],i[1]) for i in tag]<br /> print(tag)<br /> print(thai)<br /> return thai</code><br />
ลองเรียกใช้<br />
<code>print(translate("my phone"))</code><br />
ผลลัพธ์<br />
<code>[('my', 'PRON'), ('phone', 'N')]<br />['ของฉัน', 'ูโทรศัพท์']<br />['ของฉัน', 'ูโทรศัพท์']</code><br />
<br />
ตอนนี้เราสามารถแปลภาษาแบบคำเทียบคำได้แล้ว แต่พอลองประโยคแบบนี้<br />
<code>print(translate("I lost phone."))</code><br />
ผลลัพธ์<br />
<code>[('i', 'N'), ('lost', 'VERB'), ('phone', 'N'), ('.', '')]<br />[None, None, 'ูโทรศัพท์', None]<br />[None, None, 'ูโทรศัพท์', None]</code><br />
<br />
จะเห็นที่เป็น None เพราะค้นจาก lexitron.db ไม่เจอ เราจึงต้องเขียนพจนานุกรมเพิ่มเติมใส่ลงไปนอกจากเหนือจากของ LEXiTRON<br />
<code>MY_DICT = {<br /> "i,N" : "ฉัน",<br /> "lost,VERB" : "สูญเสีย"<br />}</code><br />
และปรับปรุงฟังก์ชัน word2thai ได้ดังนี้<br />
<code>def word2thai(word:str,tag:str)->str:<br />
word = word.lower()<br />
if word+","+tag in list(MY_DICT.keys()): # ถ้ามีคำแปลและ postag นี้ใน dict<br />
return MY_DICT[word+","+tag]<br />
elif word == '.':<br />
return ''<br />
elif tag == '':<br />
find = c.execute("SELECT * FROM eng2thai WHERE esearch='%s'" % (word))<br />
else:<br />
find = c.execute("SELECT * FROM eng2thai WHERE esearch='%s' and ecat='%s'" % (word,tag))<br />
for row in find:<br />
if '(' not in row[3] and 'คำ' not in row[3]:<br />
return row[3]</code><br />
ลอง<br />
<code>print(translate("I lost phone."))</code><br />
ผลลัพธ์<br />
<code>[('i', 'N'), ('lost', 'VERB'), ('phone', 'N'), ('.', '')]<br />['ฉัน', 'สูญเสีย', 'ูโทรศัพท์', '']<br />['ฉัน', 'สูญเสีย', 'ูโทรศัพท์', '']</code><br />
<br />
ลองเล่น CoLab ส่วนแปลคำต่อคำ ได้ที่ <a href="https://colab.research.google.com/drive/1_hjtUxlVRWwJdK4QhlxwnwWTVDApCHsl" rel="nofollow" target="_blank">https://colab.research.google.com/drive/1_hjtUxlVRWwJdK4QhlxwnwWTVDApCHsl </a><br />
<br />
<br />
<h3>
ส่วนที่ 2 แปลภาษาตามกฎไวยากรณ์</h3>
พอเรามาลองประโยคที่ซับซ้อนขึ้นมา<br />
<code>print(translate("I lost my phone."))</code><br />
ผลลัพธ์<br />
<code>[('i', 'N'), ('lost', 'VERB'), ('my', 'PRON'), ('phone', 'N'), ('.', '')]<br />
['ฉัน', 'สูญเสีย', 'ของฉัน', 'ูโทรศัพท์', '']<br />
['ฉัน', 'สูญเสีย', 'ของฉัน', 'ูโทรศัพท์', '']</code><br />
<br />
จะเห็นได้ว่า การแปลภาษาแบบคำต่อคำ
ไม่สามารถแปลให้เข้าใจได้เมื่อประโยคมีความซับซ้อยขึ้น
จึงต้องเขียนกฎเทียบไวยากรณ์ภาษาอังกฤษกับภาษาไทยเพิ่มขึ้นมา<br />
<br />
<br />
ก่อนอื่น เรามาเทียบไวยากรณ์ที่ได้จากประโยค I lost my phone. กัน<br />
<div style="text-align: center;">
<span style="color: orange;">I</span> <span style="color: blue;">lost</span> <span style="color: purple;">my</span> <span style="color: red;">phone</span>.</div>
<div style="text-align: center;">
<span style="color: orange;">N</span> <span style="color: blue;">VERB</span> <span style="color: purple;">PRON</span> <span style="color: red;">N</span></div>
<div style="text-align: center;">
<span style="color: orange;">ฉัน</span> <span style="color: blue;">สูญเสีย</span> <span style="color: purple;">ของฉัน</span> <span style="color: red;">โทรศัพท์</span></div>
แปลให้คำแปลออกมาเข้าใจง่ายตามภาษาไทยจะได้<br />
<div style="text-align: center;">
<span style="color: orange;">N</span> <span style="color: blue;">VERB</span> <span style="color: red;">N </span><span style="color: red;"><span style="color: purple;">PRON</span> </span></div>
<div style="text-align: center;">
<span style="color: red;"><span style="color: purple;"></span> </span></div>
<div style="text-align: center;">
<span style="color: orange;">ฉัน</span> <span style="color: blue;">สูญเสีย</span> <span style="color: red;">โทรศัพท์ </span><span style="color: red;"><span style="color: purple;">ของฉัน</span></span></div>
ดังนั้น "N VERB PRON N" ควรจัดเรียงใหม่เป็น "N VERB N PRON" เพื่อให้ประโยคภาษาอังกฤษที่แปลออกมาอ่านเข้าใจในภาษาไทย<br />
<br />
ส่วนโค้ด เราจะเทียบไวยากรณ์อย่างไร หลาย ๆ คนคงนึกถึง CFG เทียบ Tree
ไวยากรณ์ แต่บทความนี้เราเน้นความง่ายเป็นหลัก
โดยใช้การเทียบไวยากรณ์กับไวยากรณ์เลย <br />
<br />
พอได้ไวยากรณ์ที่เทียบกันแล้วเราจึงเขียนกฎขึ้นมาได้ดังนี้<br />
<code>rule = {<br /> "N VERB PRON N2" : "N VERB N2 PRON" # N2 คือ Noun ตัวที่ 2<br />}</code><br />
เขียนนำไวยากรณ์ไปเทียบ การทำงาน คือ นำ part of speech ออกมาเป็น str แล้วใช้ rule เทียบ แล้วส่งไวยากรณ์ที่จัดเรียงไว้ที่ตรงกับกฎไวยากรณ์ออกมาจัดเรียงประโยคอีกครั้ง<br />
<code>def sent2thai(listsent:list)->list: # จัดเรียงประโยคภาษาอังกฤษ -> ภาษาไทย [(คำ , ชนิดของคำ),...]<br /> i_d = {}<br /> g = []<br /> d = {}<br /><br /> for i in listsent:<br /> #print(i)<br /> word = i[0]<br /> tag = i[1]<br /> temp=""<br /> if tag not in list(i_d.keys()):<br /> temp = tag<br /> i_d[tag]=2<br /> else:<br /> temp = tag + str(i_d[tag])<br /> i_d[tag]+=1<br /> d[temp] = word<br /> g.append(temp)<br /> g=' '.join(g)<br /> if g in list(rule.keys()):<br /> g = rule[g]<br /> listnew = g.split(' ')<br /> sent = [d[i] for i in listnew]<br /> return sent</code><br />
ไปปรับแต่ง translate โดยเปลี่ยนแปลงโค้ดเป็น<br />
<code>def translate(sent:str)->list: <br /> sent = sent.lower()<br /> token = nltk.word_tokenize(sent)<br /> tag = [(i[0],tag2lexitron[i[1]]) for i in nltk.pos_tag(token,tagset='universal')]<br /> thai = [(word2thai(i[0],i[1]), i [1]) for i in tag]<br /> print(tag)<br /> print(thai)<br /> return sent2thai(thai)</code><br />
ลองเรียกใช้งาน<br />
<code>print(translate("I lost my phone"))</code><br />
ผลลัพธ์<br />
<code>[('i', 'N'), ('lost', 'VERB'), ('my', 'PRON'), ('phone', 'N')]<br />[('ฉัน', 'N'), ('สูญเสีย', 'VERB'), ('ของฉัน', 'PRON'), ('ูโทรศัพท์', 'N')]<br />N VERB PRON N2<br />['ฉัน', 'สูญเสีย', 'ูโทรศัพท์', 'ของฉัน']</code><br />
เรียบร้อย ประโยคที่เราแปลสามารถจัดเรียงคำแปลตามกฎไวยากรณ์ได้อย่างสวยงาม<br />
<br />
ลองเล่น CoLab ส่วนที่ 2 แปลภาษาตามกฎไวยากรณ์ ได้ที่ <a href="https://colab.research.google.com/drive/1xO9Tt21U06vacyjSn9RSJx03dn9O9daP" rel="nofollow" target="_blank">https://colab.research.google.com/drive/1xO9Tt21U06vacyjSn9RSJx03dn9O9daP</a><br />
<br />
เนื่องจากภาษามีกฎไวยากรณ์เยอะมาก ๆ และข้อยกเว้นมากมาย เช่น สำนวนต่าง ๆ เป็นต้น ยากที่จะเขียนกฎไวยากรณ์แปลได้ครบทุกไวยากรณ์และครบทุกกฎ การแปลภาษาด้วยเครื่องทางสถิติ (statistical machine translation) จึงได้รับความนิยมในยุคต่อมา เนื่องจากเราไม่ต้องมาเขียนไวยากรณ์เทียบแบบนี้<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><img alt="สำนวน "raining cats and dogs" เป็นอีกข้อยกเว้น หากเราจะทำโปรแกรมแปลภาษาอังกฤษเป็นภาษาไทยด้วยกฎไวยากรณ์" border="0" data-original-height="668" data-original-width="1024" height="416" imageanchor="1" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgp5GPHbhCO3MDQJf4RtgkKGT2N-0KdPG4zHbYXAktZQwTv-4GfZp24nOY8u0Ca3wlxLP8uXRbs3EYFSZ9vVLrjje0GyUB0pwyXAXVulz2XwBQlsfORhm9fQXQ2UuVp-9CmPfoXEMzRihA/s640/1024px-George_Cruikshank_-_Very_unpleasant_Weather.jpg" style="margin-left: auto; margin-right: auto;" title="" width="640" /></td></tr>
<tr><td class="tr-caption" style="text-align: center;">สำนวน "raining cats and dogs" เป็นอีกข้อยกเว้น หากเราจะทำโปรแกรมแปลภาษาอังกฤษเป็นภาษาไทยด้วยกฎไวยากรณ์ ที่มารูป : <a href="https://commons.wikimedia.org/wiki/File:George_Cruikshank_-_Very_unpleasant_Weather.jpg" rel="nofollow" target="_blank">File:George Cruikshank - Very unpleasant Weather.jpg</a></td></tr>
</tbody></table>
<u><b>ToDo สำหรับผู้อ่าน</b></u><br />
<ul>
<li>ปรับปรุงวิธีการแปลให้การแปลดียิ่งขึ้น</li>
<li>ปรับปรุงการประมวลผลคำก่อนนำไปแปล เช่น ตัด -ing หรือ -ed ทิ้ง, แปลคำกริยาให้เป็นช่องที่ 1 เป็นต้น</li>
<li>ปรับปรุงให้รองรับการแปลสำนวน</li>
<li>เปลี่ยนเป็นแปลจากภาษาไทยเป็นภาษาอังกฤษ (ยาก)</li>
</ul>
เขียนโดย นาย วรรณพงษ์ ภัททิยไพบูลย์<br />
นักศึกษาสาขาวิทยาการคอมพิวเตอร์และสารสนเทศ<br />
คณะวิทยาศาสตร์ประยุกต์และวิศวกรรมศาสตร์<br />
มหาวิทยาลัยขอนแก่น วิทยาเขตหนองคายwannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-20823878783686972962020-04-08T20:09:00.000+07:002020-04-08T20:09:07.956+07:00ดึงข้อความจากไฟล์ PDF ด้วย PDFBox ใน Pythonสวัสดีผู้อ่านทุกท่านครับ วันนี้ผมจะพาผู้อ่านไปเขียนโปรแกรมภาษา Python สำหรับดึงข้อความจากไฟล์ PDF ด้วย PDFBox กัน<br />
<a name='more'></a>Apache PDFBox เป็นชุดคำสั่งสำหรับจัดการกับไฟล์ PDF โดยสามารถใช้สร้าง อ่าน แก้ไข แบ่ง รวม ไฟล์ PDF พัฒนาบนภาษา Java และแน่นอนว่าใช้ Apache License 2.0<br />
<br />
สำหรับการใช้งานกับ Python เราสามารถดึงข้อความออกจากไฟล์ PDF ได้โดยใช้โมดูลที่ชื่อว่า python-pdfbox<br />
<b><br /></b>
<b>การติดตั้ง</b><br />
ก่อนอื่นให้ผู้อ่านติดตั้ง JAVA JDK ก่อน และตั้งค่า path ชื่อ JAVA_HOME ให้เรียบร้อย<br />
แล้วโหลด Apache PDFBox เป็นไฟล์ pdfbox-app.jar จาก <a href="https://pdfbox.apache.org/download.cgi" rel="nofollow" target="_blank">https://pdfbox.apache.org/download.cgi</a> วางไว้ในโฟลเดอร์ แล้วสร้าง path ชื่อ PDFBOX ชี้ไปยังโฟลเดอร์ที่เก็บไฟล์ Apache PDFBox นามสกุล jar<br />
<br />
จากนั้นให้ติดตั้ง python-pdfbox ด้วยคำสั่ง<br />
<blockquote class="tr_bq">
pip install python-pdfbox</blockquote>
เรามาลองดึงไฟล์ PDF กัน<br />
<br />
ผมต้องการดึงข้อความจาก <a href="https://ddc.moph.go.th/viralpneumonia/situation.php/file/situation/situation-no95-070463.pdf" rel="nofollow" target="_blank">รายงานสถานการณ์โรคติดเชื้อไวรัสโคโรนา 2019 ฉบับที่ 95 วันที่ 7 เมษายน 2563 ของกรมควบคุมโรค</a> ที่เป็นไฟล์ PDF<br />
<div class="separator" style="clear: both; text-align: center;">
<img alt="" border="0" data-original-height="444" data-original-width="956" height="296" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgSCE0xVV_WECQbFLn3eUaLb9YULJDgcc0sCNZPsKhb-T5QiZsWblSWC4FYnhAmWNh3TILARn-ueQBrwiPpCfxCW1ANZXjelaIpa5hf9MXVOdvkJOtbgIcoqmi6aottkRZTrlueW-dmu2w/s640/Annotation+2020-04-08+200754.png" title="ดึงข้อความจากไฟล์ PDF ด้วย PDFBox ใน Python" width="640" /></div>
<br />
ผมโหลดไฟล์ situation-no95-070463.pdf มา แล้วลองเขียนโปรแกรมดึงข้อความจากไฟล์ PDF ดังนี้<br />
<br />
<code>import pdfbox<br />
p = pdfbox.PDFBox()<br />
p.extract_text('situation-no95-070463.pdf',output = "data.txt") # ดึงออกมาเป็นไฟล์ txt ชื่อ data.txt</code><br />
ผลลัพธ์<br />
<div class="separator" style="clear: both; text-align: center;">
<img alt="ไฟล์ที่ได้จากการดึงข้อความจากไฟล์ PDF" border="0" data-original-height="194" data-original-width="669" height="184" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhOlc3xYsvRJbA-K43IFOQPGfO1GVAj8gMujCF1mBZydTlG1Ic2b8ClRhwlo85oMDZRNcClf9WvLMUIKR0KYDECX3lQ6vkBTVv4fgUPSL5k9gipqWnOOOZORUZJtaw0GlJ-qgfwTQLZBIE/s640/Annotation+2020-04-08+200531.png" title="" width="640" /></div>
<br />
เราจะได้ข้อความที่อยู่ในไฟล์ PDF ออกมา ค่อนข้างเกือบสมบูรณ์<br />
<br />
อธิบายคำสั่ง<br />
extract_text(input_path, output_path='',<br />
password=None, encoding=None, html=False, sort=False,<br />
ignore_beads=False, start_page=1, end_page=None, console=False)<br />
<ul>
<li>input_path - เป็นที่ตั้งไฟล์ PDF</li>
<li>output_path - เป็นที่ตั้งผลลัพธ์ไฟล์</li>
<li>password - รหัสผ่าน PDF</li>
<li>encoding - encoding ของไฟล์</li>
<li>html - output เป็น html ถ้าเป็็น True</li>
<li>sort - จัดเรียงข้อความ</li>
<li>ignore_beads - ignore separation โดย bead </li>
<li>start_page - หน้าที่เริ่ม</li>
<li>end_page - หน้าที่สิ้นสุด</li>
<li>console - ถ้า True จะโชว์หน้า console</li>
</ul>
นอกจากนั้นยังมีคำสั่ง<br />
<code>p.pdf_to_images('situation-no95-070463.pdf') # แปลง pdf แต่ละหน้าเป็นรูปภาพ<br />
p.extract_images('situation-no95-070463.pdf') # ดึงภาพจาก PDF</code><br />
<br />
<br />
ลองเล่น Colab บทความนี้ได้ที่ <a href="https://colab.research.google.com/drive/1G5jTALHlGE9e7dFjJ40JQax39tY3yKsI" rel="nofollow" target="_blank">https://colab.research.google.com/drive/1G5jTALHlGE9e7dFjJ40JQax39tY3yKsI</a><br />
<br />
อ่านเอกสารการใช้งาน python-pdfbox ได้ที่ <a href="https://github.com/lebedov/python-pdfbox" rel="nofollow" target="_blank">https://github.com/lebedov/python-pdfbox</a>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0tag:blogger.com,1999:blog-2940971822351202057.post-39200040695919992772020-03-02T19:20:00.002+07:002020-03-02T19:20:32.268+07:00สร้างแพ็คเกจ deb จากแพ็คเกจ Python ง่าย ๆ ด้วย Pythonวันนี้เราจะมาสร้างแพ็คเกจ deb จากแพ็คเกจ Python ง่าย ๆ ด้วย Python กัน<br />
<a name='more'></a><br />
<u><b><br /></b></u>
<br />
<h3>
<u><b>แพ็คเกจ deb คืออะไร?</b></u></h3>
แพ็คเกจ deb เป็นไฟล์แพ็คเกจสำหรับติดตั้งโมดูลในฝั่ง Debian กับ Ubuntu ใน Linux<br />
<br />
ในการสร้างแพ็คเกจ deb จากแพ็คเกจ Python จะต้องทำบนระบบปฎิบัติการสาย Debain หรือ Ubuntu เท่านั้น และจะต้องลงโมดูล wheel2deb ช่วยในการแปลงแพ็คเกจ whelel ของ Python ไปเป็น deb<br />
<br />
ให้ทำการติดตั้งแพ็คเกจสำหรับสร้างแพ็คเกจ deb ก่อนใช้งาน ด้วยคำสั่ง<br />
<blockquote class="tr_bq">
$ sudo apt install -y python3-apt apt-file dpkg-dev fakeroot build-essential devscripts debhelper</blockquote>
<br />
wheel2deb เป็นเครื่องมือแปลงแพ็คเกจ whelel ของ Python ไปเป็นแพ็คเกจ deb<br />
ติดตั้งได้ด้วยคำสั่ง<br />
<blockquote class="tr_bq">
$ pip install wheel2deb</blockquote>
<br />
จากนั้นให้โหลดโมดูลที่เป็นไฟล์ .whl หรือ build โมดูลให้เป็น wheel ก่อน<br />
<br />
<h3>
วิธีการ Build โมดูล Python ให้เป็น Wheel</h3>
ให้เปิดเทอร์มินัลหรือ cmd ในโฟลเดอร์เดียวกับไฟล์ติดตั้งโมดูลที่มี setup.py แล้วใช้คำสั่ง<br />
<blockquote class="tr_bq">
python setup.py bdist_wheel</blockquote>
จะได้โฟลเดอร์ dist ซึ่งภายในมีไฟล์ .whl ให้พร้อมสำหรับแปลงให้เป็นไฟล์ deb<br />
<br />
<h3>
วิธีการโหลดโมดูลที่เป็นไฟล์ .whl จาก PIP</h3>
ให้ใช้คำสั่ง<br />
<blockquote class="tr_bq">
pip wheel โมดูล</blockquote>
<br />
<h3>
วิธีการแพ็คเกจ deb จากแพ็คเกจ Python</h3>
<br />
ให้นำทุกไฟล์มารวมไว้ในโฟลเดอร์เดียวกัน โดยจะต้องโหลด wheel หรือ Build ทุกโมดูลที่ใช้ในแพ็คเกจ Python ให้ครบทุกโมดูลในโฟลเดอร์เดียวกัน แล้วใช้คำสั่ง<br />
<blockquote class="tr_bq">
wheel2deb --map attrs=attr</blockquote>
จากนั้นจะได้ไฟล์ debian source packages ในโฟลเดอร์ output จากนั้นใช้คำสั่ง build ให้เป็นแพ็คเกจ deb ด้วยคำสั่ง<br />
<blockquote class="tr_bq">
wheel2deb build</blockquote>
ภายในโฟลเดอร์ output จะประกอบไปด้วยไฟล์แพ็คเกจ deb ที่จากแพ็คเกจ Python ให้นำไปใช้งานกัน<br />
<h3>
ตัวอย่างการสร้างแพ็คเกจ deb จากแพ็คเกจ Python</h3>
ขอยกตัวอย่างการ build แพ็คเกจ PyThaiNLP ให้เป็นแพ็คเกจ deb สามารถทำได้ง่าย ๆ โดยดูตาม Colab ดังนี้ได้เลย <a href="https://colab.research.google.com/drive/1MiJ62y_hwoe9CxnCad1PWZzxwtknWFqr" rel="nofollow" target="_blank">https://colab.research.google.com/drive/1MiJ62y_hwoe9CxnCad1PWZzxwtknWFqr</a><br />
<br />
อ่านรายละเอียด wheel2deb ได้ที่ <a href="https://pypi.org/project/wheel2deb/" rel="nofollow" target="_blank">https://pypi.org/project/wheel2deb/</a>wannaphonghttp://www.blogger.com/profile/06466348192953662407noreply@blogger.com0