Unknown model· unknown
from ShareGPT 90K (shared ChatGPT conversations)
我有一個 CSV 檔案, 共有兩個欄位, 第1欄是編號、第2欄是網址, 幫我寫一個 Python 程式, 可以把CSV檔裡面網址自動轉成短網址, 再產生容錯率10%左右的…
- User
我有一個 CSV 檔案, 共有兩個欄位, 第1欄是編號、第2欄是網址, 幫我寫一個 Python 程式, 可以把CSV檔裡面網址自動轉成短網址, 再產生容錯率10%左右的 QRCode, 存成解析度 800X800 的 PNG 檔, 然後用編號欄位的編號來存檔
- Assistant
你可以使用以下的 Python 程式來完成你的需求。首先,你需要安裝一些必要的套件,如
pandas、qrcode和requests。請使用以下指令安裝套件:bashpip install pandas qrcode requests然後,你可以使用以下的程式來讀取 CSV 檔案,將網址轉換為短網址,生成 QRCode,並根據編號欄位的編號將其保存為 800x800 解析度的 PNG 檔案:
pythonimport pandas as pd import qrcode import requests import io import os def shorten_url(url): api_url = "https://tinyurl.com/api-create.php?url=" response = requests.get(api_url + url) if response.status_code == 200: return response.text else: return None def create_qrcode(url, error_correction, output_file): qr = qrcode.QRCode( version=None, error_correction=error_correction, box_size=10, border=4, ) qr.add_data(url) qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white").resize((800, 800)) img.save(output_file) def main(csv_file): df = pd.read_csv(csv_file) for index, row in df.iterrows(): id = row[0] url = row[1] short_url = shorten_url(url) if short_url: output_file = f"{id}.png" create_qrcode(short_url, qrcode.constants.ERROR_CORRECT_Q, output_file) print(f"QRCode for ID {id} saved as {output_file}") else: print(f"Error shortening URL for ID {id}") if __name__ == "__main__": csv_file = "your_csv_file.csv" # 請將此處替換為你的 CSV 檔案名稱 main(csv_file)請記得將
your_csv_file.csv替換為你的 CSV 檔案名稱。這個程式會為每個網址生成一個具有容錯率 10%(qrcode.constants.ERROR_CORRECT_Q)的 QRCode,並將其保存為 800x800 解析度的 PNG 檔案。 - User
會出現底下錯誤TypeError: can only concatenate str (not "float") to str
- Assistant
這個錯誤可能是由於在 CSV 檔案中的某些欄位有缺失值,導致 Pandas 讀取時將數值讀成浮點數。為了避免這個問題,我們可以在讀取 CSV 檔案時將這些欄位強制轉換為字串類型。請嘗試使用以下修改過的
main函式:pythondef main(csv_file): # 將所有欄位強制轉換為字串類型 dtype = {0: str, 1: str} df = pd.read_csv(csv_file, dtype=dtype) for index, row in df.iterrows(): id = row[0] url = row[1] short_url = shorten_url(url) if short_url: output_file = f"{id}.png" create_qrcode(short_url, qrcode.constants.ERROR_CORRECT_Q, output_file) print(f"QRCode for ID {id} saved as {output_file}") else: print(f"Error shortening URL for ID {id}") if __name__ == "__main__": csv_file = "your_csv_file.csv" # 請將此處替換為你的 CSV 檔案名稱 main(csv_file)這樣應該可以解決錯誤。若問題仍然存在,請檢查 CSV 檔案中是否有其他異常