2024年4月23日 星期二

利用pywin32套件來操作Words, Excel, PowerPoint

1.讀取Words檔案,顯示內容並利用Words內建的統計功能來計算字數、字元數、頁數。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from win32com.client import Dispatch
import os

app = Dispatch("Word.Application")
app.Visible = 1
app.DisplayAlerts = 0
docx = app.Documents.Open(os.getcwd()+"\\test.docx")
print('段落數: ', docx.Paragraphs.count)
print('文章內容: ')
for i in range(len(docx.Paragraphs)):
    para = docx.Paragraphs[i]
    print(para.Range.text)
words = app.ActiveDocument.ComputeStatistics(0)
chars = app.ActiveDocument.ComputeStatistics(3)
pages = app.ActiveDocument.ComputeStatistics(2)
print('字數統計:', words)
print('字元統計:', chars)
print('頁數統計:', pages)
docx.Close()
app.Quit()

執行結果:
段落數:  3
文章內容: 
國立虎尾科技大學 (英文:National Formosa University),簡稱虎科、虎科大、虎尾科大、NFU,別稱國立福爾摩沙大學,位於雲林縣虎尾鎮的國立科技大學。前身為雲林工專,為昔日三大工專之一。

目前設有目前有工程、管理、電機資訊、文理四個學院。為雲林國立大學聯盟以及臺灣國立大學系統成員。

(以上資料摘自維基百科)

字數統計: 137
字元統計: 161
頁數統計: 1

2. 把九九乘法表存到Excel檔案中
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from win32com.client import Dispatch
import os

app = Dispatch("Excel.Application")
app.Visible = 1
app.DisplayAlerts = 0
xlsx = app.Workbooks.Add()
sheet = xlsx.Worksheets(1)
for i in range(1,10):
    for j in range(1,10):
        sheet.Cells(i, j).Value = i*j
xlsx.SaveAs(os.getcwd()+"\\99.xlsx")
xlsx.Close(False)
app.Quit()

執行結果:

3.讀取99.xls檔案
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import win32com
from win32com.client import Dispatch
import os

app = win32com.client.Dispatch("Excel.Application")
app.Visible = 1
app.DisplayAlerts = 0
xlsx = app.Workbooks.Open(os.getcwd()+"\\99.xlsx")
sheet = xlsx.Worksheets(1)
row = sheet.UsedRange.Rows.Count
col = sheet.UsedRange.Columns.Count
for i in range(row):
    for j in range(col):
        if int(sheet.Cells(i+1, j+1).Value)<10:
            print(' ', end='')
        print(int(sheet.Cells(i+1, j+1).Value), end=' ')
    print()
xlsx.Close(False)
app.Quit()

執行結果:

4.每隔1秒鐘,自動播放1張投影片


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from win32com.client import Dispatch
import time, os

app = Dispatch("PowerPoint.Application")
app.Visible = 1
app.DisplayAlerts = 0
pptx = app.Presentations.Open(os.getcwd()+"\\test.pptx")
pptx.SlideShowSettings.Run()
for i in range(len(pptx.slides)):
    time.sleep(1)
    pptx.SlideShowWindow.View.Next()
pptx.SlideShowWindow.View.Exit()
os.system('taskkill /F /IM POWERPNT.EXE')


2024年4月22日 星期一

在Django中設定和存取Session的內容

參考資料:Python架站特訓班django最強實戰
1.在CookieSession/CookieSession/urls.py,增加set_session和get_session兩個路徑對應到函式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
"""
URL configuration for CookieSession project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from CookieSessionApp.views import index, set_cookie, get_cookie, set_session, get_session

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index),
    path('set_cookie/<str:key>/<str:value>/', set_cookie),
    path('get_cookie/<str:key>/', get_cookie),
    path('set_session/<str:key>/<str:value>/', set_session),
    path('get_session/<str:key>/', get_session),
]

2.在CookieSession/CookieSessionApp/views.py,增加set_session和get_session兩個函式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from django.shortcuts import render
from django.http import HttpResponse
import datetime

# Create your views here.

def set_cookie(request,key=None,value=None):
	response = HttpResponse('Cookie 儲存完畢!')
	response.set_cookie(key,value.encode('utf-8').decode('latin-1'))
	return response

def get_cookie(request,key=None):
	if key in request.COOKIES:
		return HttpResponse('%s : %s' %(key,request.COOKIES[key].encode('latin-1').decode('utf-8')))
	else:
		return HttpResponse('Cookie 不存在!')
	
def index(request):
	if "counter" in request.COOKIES:
		counter=int(request.COOKIES["counter"])
		counter+=1
	else:		
		counter=1
	response = HttpResponse('歡迎光臨,今日瀏覽次數:' + str(counter))		
	tomorrow = datetime.datetime.now() + datetime.timedelta(days = 1)
	tomorrow = datetime.datetime.replace(tomorrow, hour=0, minute=0, second=0)
	expires = datetime.datetime.strftime(tomorrow, "%a, %d-%b-%Y %H:%M:%S GMT") 
	response.set_cookie("counter",counter,expires=expires)
	return response

def set_session(request,key=None,value=None):
	response = HttpResponse('Session 儲存完畢!')
	request.session[key]=value
	return response
	
def get_session(request,key=None):
	if key in request.session:
		return HttpResponse('%s : %s' %(key,request.session[key]))
	else:
		return HttpResponse('Session 不存在!')	

3.測試
3.1 http://127.0.0.1:8000/set_session/name/虎尾鎮/

3.2 http://127.0.0.1:8000/get_session/name/



2024年4月21日 星期日

在Django中設定和存取Cookies中的中文字

參考資料:Python架站特訓班django最強實戰

上一篇文章:在Django中使用Cookies來計算今天瀏覽次數

想從剛從建立專案開始,務必參考上一篇文章。

1.在CookieSession/CookieSession/urls.py,增加set_cookie和get_cookie兩個路徑對應到函式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
"""
URL configuration for CookieSession project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from CookieSessionApp.views import index, set_cookie, get_cookie

urlpatterns = [
    path('admin/', admin.site.urls),
    	path('', index),
        path('set_cookie/<str:key>/<str:value>/', set_cookie),
	path('get_cookie/<str:key>/', get_cookie),
]

2.在CookieSession/CookieSessionApp/views.py,增加set_cookie和get_cookie兩個函式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from django.shortcuts import render
from django.http import HttpResponse
import datetime

# Create your views here.

def set_cookie(request,key=None,value=None):
	response = HttpResponse('Cookie 儲存完畢!')
	response.set_cookie(key,value.encode('utf-8').decode('latin-1'))
	return response

def get_cookie(request,key=None):
	if key in request.COOKIES:
		return HttpResponse('%s : %s' %(key,request.COOKIES[key].encode('latin-1').decode('utf-8')))
	else:
		return HttpResponse('Cookie 不存在!')
	
def index(request):
	if "counter" in request.COOKIES:
		counter=int(request.COOKIES["counter"])
		counter+=1
	else:		
		counter=1
	response = HttpResponse('歡迎光臨,今日瀏覽次數:' + str(counter))		
	tomorrow = datetime.datetime.now() + datetime.timedelta(days = 1)
	tomorrow = datetime.datetime.replace(tomorrow, hour=0, minute=0, second=0)
	expires = datetime.datetime.strftime(tomorrow, "%a, %d-%b-%Y %H:%M:%S GMT") 
	response.set_cookie("counter",counter,expires=expires)
	return response	

3.測試
3.1 http://127.0.0.1:8000/set_cookie/name/虎尾鎮/

3.2 http://127.0.0.1:8000/get_cookie/name/



在Django中使用Cookies來計算今天瀏覽次數

參考資料:Python架站特訓班django最強實戰


1.打開cmd建立Django專案

1.1 安裝django套件,已安裝可以省略

pip install django

1.2 建立CookieSession專案

django-admin startproject CookieSession

1.3 建立CookieSession專案的App

python manage.py startapp CookieSessionApp

1.4 啟動網站

python manage.py migrate

python manage.py runserver

1.5 打開瀏覽器,輸入127.0.0.1:8000


2. 更換預設首頁

安裝APP, CookieSession/CookieSession/settings.py,黃底字是新增部份。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
"""
Django settings for CookieSession project.

Generated by 'django-admin startproject' using Django 4.2.3.

For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-^9frr%qp+(f(1z0k09w&*!y8de-xk440#1aek344)w-w8gwt^m'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'CookieSessionApp',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'CookieSession.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'CookieSession.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

2.2 增加首頁URL對應到index函式的路徑到CookieSession/urls.py,黃底字是新增部份。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
"""
URL configuration for CookieSession project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from CookieSessionApp.views import index

urlpatterns = [
    path('admin/', admin.site.urls),
    	path('', index),
]

2.3 新增index函式到CookieSession/CookieSessionApp/views.py

1
2
3
4
5
6
7
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):
	response = HttpResponse('歡迎光臨')		
	return response	

2.4 更新瀏覽器-127.0.0.1:8000內容

3.加上Cookies
3.1 修訂在CookieSession/CookieSessionApp/views.py的index函式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from django.shortcuts import render
from django.http import HttpResponse
import datetime

# Create your views here.
def index(request):
	if "counter" in request.COOKIES:
		counter=int(request.COOKIES["counter"])
		counter+=1
	else:		
		counter=1
	response = HttpResponse('歡迎光臨,今日瀏覽次數:' + str(counter))		
	tomorrow = datetime.datetime.now() + datetime.timedelta(days = 1)
	tomorrow = datetime.datetime.replace(tomorrow, hour=0, minute=0, second=0)
	expires = datetime.datetime.strftime(tomorrow, "%a, %d-%b-%Y %H:%M:%S GMT") 
	response.set_cookie("counter",counter,expires=expires)
	return response	

3.2 更新瀏覽器-127.0.0.1:8000內容

3.3 查看Cookies,在執行網頁內容中按下右鍵,選擇'檢查'功能表,再選擇應用程式,即可以查看。



2024年4月8日 星期一

Python雙迴圈基礎教材

 1.

1
2
3
4
for i in range(5):
    for j in range(i+1):
        print('*', end='')
    print()

執行結果:



2.
1
2
3
4
for i in range(5):
    for j in range(5-i):
        print('*', end='')
    print()

執行結果:



3.

1
2
3
4
5
6
7
8
for i in range(5):
    for j in range(i+1):
        print('*', end='')
    print()
for i in range(5):
    for j in range(5-i-1):
        print('*', end='')
    print()

執行結果:


4.

1
2
3
4
5
6
for i in range(5):
    for j in range(5-i-1):
        print(' ', end='')
    for j in range(i+1):
        print('*', end='')
    print()

執行結果:

5.

1
2
3
4
5
6
for i in range(5):
    for j in range(i):
        print(' ', end='')
    for j in range(5-i):
        print('*', end='')
    print()

執行結果:


6.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
for i in range(5):
    for j in range(5-i-1):
        print(' ', end='')
    for j in range(i+1):
        print('*', end='')
    print()
for i in range(5):
    for j in range(i+1):
        print(' ', end='')
    for j in range(5-i-1):
        print('*', end='')
    print()

執行結果:

7.

1
2
3
4
5
6
for i in range(5):
    for j in range(5-i-1):
        print(' ', end='')
    for j in range(i*2+1):
        print('*', end='')
    print()

執行結果:


8.

1
2
3
4
5
6
for i in range(5):
    for j in range(5-i-1):
        print(' ', end='')
    for j in range(i*2+1):
        print(str(i+1), end='')
    print()

執行結果:

9.

1
2
3
4
5
6
for i in range(5):
    for j in range(5-i-1):
        print(' ', end='')
    for j in range(i*2+1):
        print(str(j+1), end='')
    print()

執行結果:


2024年4月7日 星期日

micro:bit OLED1306 製作螢幕畫面

 電子元件有micro:bit主板、iot:bit底板、以及SSD OLED1306

OLED驅動程式:fizban99/microbit_ssd1306

程式編輯工具:micro:bit Python Editor

程式檔案管理:除了main.py外,其餘檔案來自OLED驅動程式

1.利用小畫家以128*64來設計畫面


2.改寫OLED驅動程式microbit_ssd1306/sample_images/bitmapconverter.py的程式實現轉換:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import struct
from PIL import Image
filename = 'treeart'

pic = [0x00 for _ in range(128*64)]

bmp_image = Image.open( filename+'.bmp' )

index=0
for i_horizon  in range(bmp_image.width):
    for i_vertical in range(bmp_image.height//8):
        b=0x0
        for i in range(0, 8):
            b>>=1
            if bmp_image.getpixel((i_horizon, i_vertical*8+i)) == 255:
                b |= 0x80
        pic[i_horizon+i_vertical*bmp_image.width]=b
        index+=1

newFileByteArray = bytearray(pic)
with open(filename, 'wb') as newFile:
    newFile.write(newFileByteArray)

print("Done")

3.把相關檔案載入


4.利用步驟2的程式進行轉碼,再撰寫micro:bit Python程式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from ssd1306 import initialize, clear_oled
from ssd1306_bitmap import show_bitmap
from microbit import *

initialize()
clear_oled()
while True:
    show_bitmap('microbit_logo')
    display.scroll('Welcome to ')
    show_bitmap('craft_center')
    display.scroll('National Taiwan Craft Research and Development')
    show_bitmap('nfu')
    display.scroll('National Formosa University')   
    show_bitmap('treeart')
    display.scroll('Workshop of Tree Art')  
    show_bitmap('steam')
    display.scroll('OUTSTEAM International')  
    show_bitmap('smartcreating')
    display.scroll('SmartCreating Co., Ltd.')  
    show_bitmap('goods')
    display.scroll('Taiwan Rural Goods Promotion Alliance') 

5.下載到micro:bit後,執行。


2024年4月6日 星期六

micro:bit OLED初接觸

電子元件有micro:bit主板、iot:bit底板、以及SSD OLED1306

OLED驅動程式:fizban99/microbit_ssd1306

程式編輯工具:micro:bit Python Editor

程式檔案管理:除了main.py外,其餘檔案來自OLED驅動程式


Python程式碼:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from ssd1306 import initialize, clear_oled
from ssd1306_text import add_text
from ssd1306_bitmap import show_bitmap
from microbit import *

initialize()
clear_oled()
show_bitmap('microbit_logo')
sleep(2000)
clear_oled()
add_text(0, 0, 'TreeArt:bit')
i=0
while True:
    add_text(0, 2, str(i))
    sleep(1000)
    i=i+1

執行結果:




2024年4月5日 星期五

用Python來計算中文英文的字數以及字元數

程式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Count:
    def __init__(self, str):
        self.words = 0
        self.halfwords = 0
        self.fullwords = 0
        self.charactersWithSpace = len(str)
        self.charactersWithoutSpace = len(str)
        contineflag = 0
        for c in str:
            if c == ' ':
                self.charactersWithoutSpace-=1
                contineflag = 0
            if '\u4e00' <= c <= '\u9fef':
                self.words+=1
                self.fullwords+=1
                contineflag = 0
            else:
                if contineflag == 0:
                    self.halfwords+=1
                    self.words+=1
                    contineflag = 1
                    
        
str = input("請輸入文字含中英文:")
cnt = Count(str)
print("字元數含空白", cnt.charactersWithSpace)
print("字元數不含空白", cnt.charactersWithoutSpace)
print("字數", cnt.words)
print("半型字數", cnt.halfwords)
print("全型字數", cnt.fullwords)

執行結果1:
請輸入文字含中英文:Hello World
字元數含空白 11
字元數不含空白 10
字數 2
半型字數 2
全型字數 0

執行結果2:
請輸入文字含中英文:國立虎尾科技大學
字元數含空白 8
字元數不含空白 8
字數 8
半型字數 0
全型字數 8

執行結果3:
請輸入文字含中英文:1a一2b Hello Word
字元數含空白 16
字元數不含空白 14
字數 5
半型字數 4
全型字數 1

檔案的簡易操作

 1.寫中文資料到檔案

1
2
3
4
fp=open("test.txt", "w", encoding = "UTF-8")
fp.write("好吃芋頭在雲林縣林內鄉烏塗村\n")
fp.write("好吃花生在雲林縣元長鄉和虎尾鎮")
fp.close()

2.讀取資料
1
2
3
4
5
fp=open("test.txt", "r", encoding = "UTF-8")
lines=fp.readlines()
for line in lines:
    print(line)
fp.close()

執行結果:
好吃芋頭在雲林縣林內鄉烏塗村

好吃花生在雲林縣元長鄉和虎尾鎮

3.檔案已有換行字元'\n',輸出可以不用換行
1
2
3
4
5
fp=open("test.txt", "r", encoding = "UTF-8")
lines=fp.readlines()
for line in lines:
    print(line, end="")
fp.close()

執行結果:
好吃芋頭在雲林縣林內鄉烏塗村
好吃花生在雲林縣元長鄉和虎尾鎮

4.使用with/as來讀取檔案內容
1
2
3
4
5
with open("test.txt", "r", encoding = "UTF-8") as fp:
    lines=fp.readlines()
    for line in lines:
        print(line, end="")
    fp.close()

執行結果:
好吃芋頭在雲林縣林內鄉烏塗村
好吃花生在雲林縣元長鄉和虎尾鎮

1
2
3
4
5
6
7
8
with open("test.txt", "r", encoding = "UTF-8") as fp:
    lines = fp.read().split("\n")
    line_cnt = len(lines)
    word_cnt = char_cnt = 0
    for line in lines:
        words = line.split()
        word_cnt, char_cnt = word_cnt + len(words), char_cnt + len(line)
    print("File {0} has {1} lines, {2} words, {3} characters".format("test.txt", line_cnt, word_cnt, char_cnt))

執行結果:
File test.txt has 2 lines, 2 words, 29 characters

眼尖的朋友是否覺得有問題呢?
中文字數不能用split()來計算,29字元數就是中文字數。



用Python求最大公因收和最小公倍數

 

1.找因數

1
2
3
4
5
6
a=int(input('請輸入大於零的整數:'))
if(a>0):
    for i in range(1,a+1):
        if(a%i==0):
            print(i,end=" ")
    print("")

執行結果:
請輸入大於零的整數:12
1 2 3 4 6 12 

2.利用集合生成式找因數

1
2
3
a=int(input('請輸入大於零的整數:'))
a_set={n for n in range(1,a+1) if a>0 and a%n==0}
print(a_set)

執行結果:
請輸入大於零的整數:9
{1, 3, 9}

3.找出兩數的公因數

1
2
3
4
5
a=int(input('請輸入大於零的整數A:'))
a_set={n for n in range(1,a+1) if a>0 and a%n==0}
b=int(input('請輸入大於的整數B:'))
b_set={n for n in range(1,b+1) if b>0 and b%n==0}
print(a_set & b_set)

執行結果:
請輸入大於零的整數A:12
請輸入大於的零整數B:9
{1, 3}

4.找出兩數的最大公因數

1
2
3
4
5
a=int(input('請輸入大於零的整數A:'))
a_set={n for n in range(1,a+1) if a>0 and a%n==0}
b=int(input('請輸入大於的整數B:'))
b_set={n for n in range(1,b+1) if b>0 and b%n==0}
print(max(a_set & b_set))

執行結果:
請輸入大於零的整數A:12
請輸入大於零的整數B:9
3

5.找出兩數的最小公倍數

1
2
3
4
5
a=int(input('請輸入大於零的整數A:'))
a_set={n for n in range(1,a+1) if a>0 and a%n==0}
b=int(input('請輸入大於的整數B:'))
b_set={n for n in range(1,b+1) if b>0 and b%n==0}
print(a*b//max(a_set & b_set))

執行結果:
請輸入大於零的整數A:12
請輸入大於零的整數B:9
36

6.一次輸入兩個數,找出兩數的最小公倍數

1
2
3
4
5
a,b=int(input('請輸入大於的整數(A, B):'))
print(a,b)
a_set={n for n in range(1,a+1) if a>0 and a%n==0}
b_set={n for n in range(1,b+1) if b>0 and b%n==0}
print(a*b//max(a_set & b_set))

執行結果:
請輸入大於零的整數(A, B):9, 12
Traceback (most recent call last):
  File "C:/Users/cheng-min/AppData/Local/Programs/Python/Python311/test.py", line 1, in <module>
    a,b=int(input('請輸入大於零的整數(A, B):'))
ValueError: invalid literal for int() with base 10: '9, 12'

將int()改成eval()函式:

1
2
3
4
5
a,b=eval(input('請輸入大於零的整數(A, B):'))
print(a,b)
a_set={n for n in range(1,a+1) if a>0 and a%n==0}
b_set={n for n in range(1,b+1) if b>0 and b%n==0}
print(a*b//max(a_set & b_set))

執行結果:
請輸入大於零的整數(A, B):9, 12
9 12
36

7.用自定函式來求最大公因收和最小公倍數

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def gcd(a, b):
    if b==0:
        return a
    else:
        return gcd(b, a%b)

def lcm(a, b):
    return a*b//gcd(a, b)


a,b=eval(input('請輸入大於零的整數(A, B):'))
print("gcd(",a,",",b,")=", gcd(a,b))
print("lcm(",a,",",b,")=", lcm(a,b))

執行結果:
請輸入大於零的整數(A, B):9, 12
gcd( 9 , 12 )= 3
lcm( 9 , 12 )= 36

8.利用math套件求最大公因收和最小公倍數

1
2
3
4
import math
a,b=eval(input('請輸入大於零的整數(A, B):'))
print("gcd(",a,",",b,")=", math.gcd(a,b))
print("lcm(",a,",",b,")=", math.lcm(a,b))

執行結果:
請輸入大於零的整數(A, B):9,12
gcd( 9 , 12 )= 3
lcm( 9 , 12 )= 36

9.利用sympy套件求最大公因收和最小公倍數

1
2
3
4
from sympy import *
a,b=eval(input('請輸入大於的整數(A, B):'))
print("gcd(",a,",",b,")=", gcd(a,b))
print("lcm(",a,",",b,")=", lcm(a,b))

執行結果:
Traceback (most recent call last):
  File "C:/Users/cheng-min/AppData/Local/Programs/Python/Python311/test.py", line 1, in <module>
    from sympy import *
ModuleNotFoundError: No module named 'sympy'

安裝sympy套件

執行結果:
請輸入大於零的整數(A, B):9, 12
gcd( 9 , 12 )= 3
lcm( 9 , 12 )= 36

10.改用import寫法

1
2
3
4
import sympy
a,b=eval(input('請輸入大於零的整數(A, B):'))
print("gcd(",a,",",b,")=", gcd(a,b))
print("lcm(",a,",",b,")=", lcm(a,b))

執行結果:
Traceback (most recent call last):
  File "C:/Users/cheng-min/AppData/Local/Programs/Python/Python311/test.py", line 3, in <module>
    print("gcd(",a,",",b,")=", gcd(a,b))
NameError: name 'gcd' is not defined

修改程式:

1
2
3
4
import sympy
a,b=eval(input('請輸入大於零的整數(A, B):'))
print("gcd(",a,",",b,")=", sympy.gcd(a,b))
print("lcm(",a,",",b,")=", sympy.lcm(a,b))

執行結果:
請輸入大於零的整數(A, B):9,12
gcd( 9 , 12 )= 3
lcm( 9 , 12 )= 36

為什麼要介紹sympy套件,不妨可以參考夠Python,一行指令找質數