#!/usr/bin/env python # coding: utf-8 # # วิธีทำงานโดยเปิดไฟล์แล้วอ่านทีละบรรทัด # เราสามารถใช้วิธี: # # inputfile = open(filename) # for line in inputfile: # work_on_the_line # # เช่นโค้ดข้างล่างเปิดไฟล์ `/usr/share/dict/words` แล้วอ่านทีละบรรทัด โดยที่แต่ละบรรทัดอยู่ในตัวแปร `word` ด้วยคำสั่ง `for word in inputfile:` # # # In[1]: #นับคำที่ขึ้นต้นด้วยอักษร e หรือ E inputfile = open('/usr/share/dict/words') #เปิดไฟล์ที่มีคำภาษาอังกฤษบรรทัดละหนึ่งคำ count = 0 #เริ่มนับ ยังไม่่เจออะไรเลย ดังนั้น count = 0 for word in inputfile: #อ่านเข้ามาทีละบรรทัด เก็บบรรทัดไว้ในตัวแปร word word = word.strip() #strip() จะลบตัวอักษรที่มองไม่เห็น (white spaces) ด้านหน้าและด้านหลังของคำ รวมถึงตัวอักษรขึ้นบรรทัดใหม่ (newline, \n) if word.startswith("e") or word.startswith("E"): #ถ้าเจอบรรทัดที่ขึ้นต้นด้วย e หรือ E ให้นับเพิ่มเข้าไปใน count #print(word) count = count + 1 print(f"Number of words is {count}") #รายงานผลนับใน count # ### ตัวอย่างหาว่าตัวอักษรแต่ละตัวขึ้นต้นคำภาษาอังกฤษกี่คำ # # In[2]: #วิธีนี้อ่านไฟล์ /usr/share/dict/words ซ้ำๆถึง 26 รอบ for letter in "abcdefghijklmnopqrstuvwxyz": inputfile = open('/usr/share/dict/words') count = 0 for word in inputfile: word = word.strip() if word.startswith(letter): count = count + 1 print(f"There are {count} words starting with the letter {letter}") # In[3]: #วิธีนี้อ่านไฟล์ /usr/share/dict/words รอบเดียว #ใช้ตัีวแปร count แบบประเภท dictionary (หรือเรียกอีกอย่างว่า hashed table) inputfile = open('/usr/share/dict/words') count = {} # {} แปลว่า count เป็น dictionary สามารถถูกอ้างอิงด้วยตัวอักษรและอื่นๆ ไม่จำเป็นต้องเป็นตัวเลขแบบถ้า count เป็น array lowercase_letters = "abcdefghijklmnopqrstuvwxyz" #อักษรภาษาอังกฤษ 26 ตัว for letter in lowercase_letters: count[letter] = 0 #เริ่มต้นให้จำนวนคำของทุกตัวอักษรเป็นศูนย์ก่อน for word in inputfile: word = word.strip() for letter in lowercase_letters: if word.startswith(letter): count[letter] += 1 #เหมือนกับ count[letter] = count[letter] + 1 for letter, count in count.items(): print(f"There are {count} words starting with the letter {letter}") # ### ทำผลลัพธ์ให้เหมาะกับให้คอมพิวเตอร์ไปประมวลผลต่อ # ตัวอย่างด้านบนพิมพ์ผลลัพธ์แบบเหมาะให้คนอ่าน แต่อาจนำไปใช้ในโปรแกรมอื่นๆยาก ถ้าเราจะให้ผลลัพธ์ไปใช้ในโปรแกรมอื่นๆสะดวกเราก็ควรเปลี่ยน `print(f"There are {count} words starting with the letter {letter}")` ให้เป็นรูปแบบที่อ่านง่ายด้วยโปรแกรมเช่น `print(f"{letter}:{count}")` หรือ `print(f"{letter}\t{count}")` # In[4]: inputfile = open('/usr/share/dict/words') count = {} lowercase_letters = "abcdefghijklmnopqrstuvwxyz" for letter in lowercase_letters: count[letter] = 0 for word in inputfile: word = word.strip() for letter in lowercase_letters: if word.startswith(letter): count[letter] += 1 for letter, count in count.items(): #print(f"{letter}:{count}") #แบ่งด้วย : print(f"{letter}\t{count}") #แบ่งด้วย tab (\t) # In[ ]: