2026年3月19日 星期四

用Python將有機食物樣版轉換成Django網站


 前一篇文章:下載有機食物樣版實作Django網站

轉換的Python程式是用Gemini產生。

 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
import re
import os

def convert_html_to_django(input_file, output_file):
    if not os.path.exists(input_file):
        print(f"錯誤:找不到檔案 {input_file}")
        return

    with open(input_file, 'r', encoding='utf-8') as f:
        content = f.read()

    # 1. 在檔案最上方加入 {% load static %} (如果還沒有的話)
    if "{% load static %}" not in content:
        content = "{% load static %}\n" + content

    # 2. 處理 href 和 src 屬性
    # 這裡將替換字串拆解,避免使用反斜線轉義引號
    pattern_attr = r'(href|src)=["\']((?!http|https|#|{%)[^"\']+\.(?:css|js|png|jpg|jpeg|gif|svg|webp|ico))["\']'
    
    # 使用正確的拼接方式: \1="{% static ' \2 ' %}"
    replacement_attr = r'\1="{% static ' + "'" + r'\2' + "'" + r' %}"'
    content = re.sub(pattern_attr, replacement_attr, content)

    # 3. 處理 CSS inline style 中的 url('...')
    # 修正 url() 內部的路徑轉換
    pattern_url = r'url\(["\']?((?!http|https|{%)[^"\'\)]+)["\']?\)'
    
    # 這裡改為標準字串處理,確保輸出為 url('{% static 'path' %}')
    replacement_url = "url('{% static '\\1' %}')"
    content = re.sub(pattern_url, replacement_url, content)

    # 4. 輸出轉換後的檔案
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(content)

    print(f"轉換成功!已修正轉義符號。檔案已儲存至: {output_file}")

# 執行轉換
if __name__ == "__main__":
    convert_html_to_django('index.html', 'index_django.html')


沒有留言:

張貼留言