四月 2024
1234567
891011121314
15161718192021
22232425262728
2930  

彙整

從範例學程式進階 – Python(1080808, 10)

日期:108年8月8, 10日(四、六)

時間:9:00 – 16:00

地點:樹林國小福祿樓2樓電腦教室

主題:從範例學程式進階 – Python

講師:邱昭士

公文:

Python 入門、開發環境與工具

參考用書:

PyGame

上課用線上資源及範例:

def oddfn(x):
    # return x if (x % 2 == 1) else None
    if x % 2 == 1:
        return x
    else:
        return None
mylist = [5, 10, 15, 20, 25, 30]
filter_object = filter(oddfn, mylist) # 傳回filter object
print("奇數串列: ", [item for item in filter_object])
itemlist = [item for item in mylist if oddfn(item)]
print("奇數串列: ", itemlist)
itemlist = []
for item in mylist:
    if oddfn(item):
        itemlist.append(item)
print("奇數串列: ", itemlist)

使用 Python 處理各式文件:

一、處理 Word 文件

  • 外掛模組:python-docx
  • 下載安裝:pip install python-docx
  • 程式導入:import docx
  • 線上說明:python-docx documentation

在 python-docx 模組內,將 Word 文件結構分成 3 層:

  • Document
  • Paragraph
  • Run
wdoc = docx.Document('檔案名稱')    # 建立 docx 物件 wdoc

wdoc.paragraphs

wdoc.paragraphs[n].runs

wdoc.paragraphs[n].text

wdoc.paragraphs[n].runs[m].text

二、處理 PDF 文件

  • 外掛模組:PyPDF2
  • 下載安裝:pip install PyPDF2
  • 程式導入:import PyPDF2
  • 線上說明:PyPDF2 Documentation
pdfObj = open('pdf_file', 'rb')          # 'rb' 表示以二進位方式開啟
pdfRd = PyPDF2.PdfFileReader(pdfObj)     # 讀取 PDF 內容

三、處理 Excel 文件

wb = openpyxl.load_workbook('excel_file')

allSheets = wb.get_sheet_names()

ws = wb.get_active_sheet()

ws = wb.get_sheet_by_name('2020Q3')

四、處理 CSV 文件

fn = 'csvReport.csv'
with open(fn) as csvFile:
    csvReader = csv.reader(csvFile)
    for row in csvReader:
        print("Row %s = " % csvReader.line_num, row)
fn = 'out20_7.csv'
with open(fn, 'w', newline = '') as csvFile: # 開啟csv檔案
    csvWriter = csv.writer(csvFile)          # 建立Writer物件 
    csvWriter.writerow(['Name', 'Age', 'City'])
    csvWriter.writerow(['Hung', '35', 'Taipei'])
    csvWriter.writerow(['James', '40', 'Chicago'])

網路爬蟲

PyGame 範例

PyGame 影音教學 MovingBall

學習資源:

Python Library 與第三方程式碼:

Comments are closed.