程式碼解釋器是 OpenAI 的 GPTs.x 和 ChatGPT 的進階功能,它為 AI 模型帶來了新的互動性水平。它旨在在沙盒環境中執行 Python 程式碼並提供即時結果,使其成為執行各種任務的強大工具,從數學計算到數據分析,從程式碼原型設計到互動式教學和學習 Python 程式設計。雖然由於安全原因其功能存在某些限制,但它為使用者與 ChatGPT 互動的方式提供了一系列全新的可能性。
程式碼解釋器是OpenAI開發的一種在互動式環境中執行程式碼的工具。它能夠運行Python程式碼並即時顯示結果。
程式碼解釋器可用於多種任務,包括:
ChatGPT 可以根據提供的要求產生、審查和偵錯程式碼。它還可以幫助建立程式碼並提供改進建議。此外,它可以解釋複雜的程式設計概念並幫助解決編碼問題。
雖然程式碼解釋器是一個強大的工具,但它也有一定的限制:
儘管有這些限制,程式碼解釋器是一種多功能工具,可以極大地幫助所有技能水平的程式設計師。
程式碼解釋器有幾個好處:
要執行本自述文件中提到的範例,您需要安裝一些 Python 程式庫。您可以使用 pip 安裝它們:
pip install pandas openpyxl python-docx PyPDF2 fpdf2 matplotlib pillow
程式碼解釋器可以存取特殊目錄“/mnt/data”,可以在其中讀取和寫入檔案。這可用於需要保存或載入資料的操作,例如寫入日誌、保存繪圖或載入資料以進行分析。但是,無法存取檔案系統上的其他位置。
“/mnt/data”目錄是程式碼解釋器可以存取以讀取和寫入檔案的特殊儲存位置。這對於需要持久性儲存或不同程式碼執行之間交換資料的操作特別有用。
以下是使用“/mnt/data”目錄的一些方法:
with open ( '/mnt/data/numbers.txt' , 'w' ) as file :
for num in range ( 10 ):
file . write ( str ( num ) + ' n ' )
要讀取該文件,您可以執行以下操作:
with open ( '/mnt/data/numbers.txt' , 'r' ) as file :
numbers = file . readlines ()
with open ( '/mnt/data/log.txt' , 'w' ) as file :
file . write ( 'This is a log message.' )
import matplotlib . pyplot as plt
plt . plot ([ 0 , 1 , 2 , 3 , 4 ], [ 0 , 1 , 4 , 9 , 16 ])
plt . savefig ( '/mnt/data/plot.png' )
然後,您可以直接從生成的沙箱鏈接下載圖像檔案。
請記住,任何檔案操作都需要使用“/mnt/data”路徑完成。代碼解釋器無權存取檔案系統上的任何其他位置。
借助PIL(Python Imaging Library)、OpenCV、matplotlib等各種Python庫,可以對影像進行多種操作。以下是一些範例:
from PIL import Image
import matplotlib . pyplot as plt
# Open the image file
img = Image . open ( '/mnt/data/your_image.jpg' )
# Display the image
plt . imshow ( img )
plt . axis ( 'off' ) # Turn off the axis
plt . show ()
# Resize the image
img_resized = img . resize (( new_width , new_height ))
# Rotate the image
img_rotated = img . rotate ( angle )
# Flip the image
img_flipped = img . transpose ( Image . FLIP_LEFT_RIGHT )
# Convert the image to grayscale
img_gray = img . convert ( 'L' )
from PIL import ImageEnhance
# Increase the brightness
enhancer = ImageEnhance . Brightness ( img )
img_brighter = enhancer . enhance ( 1.5 )
from PIL import ImageFilter
# Apply a filter
img_blurred = img . filter ( ImageFilter . GaussianBlur ( radius = 5 ))
# Get the histogram
hist = img . histogram ()
# Merge images
img_merged = Image . merge ( 'RGB' , [ img1 , img2 , img3 ])
處理 Excel 檔案是一項常見任務,從資料分析到產生報表。以下是使用 Python 對 Excel 檔案進行基本和進階操作的指南:
要讀取和寫入 Excel 文件,通常使用pandas
和openpyxl
。以下是讀取和寫入 Excel 檔案的方法:
import pandas as pd
# Load an Excel file
df = pd . read_excel ( '/mnt/data/example.xlsx' )
# Display data
print ( df . head ())
###將資料寫入 Excel 檔案:
# Create a DataFrame
data = { 'Name' : [ 'Alice' , 'Bob' , 'Charlie' ], 'Age' : [ 25 , 30 , 35 ]}
df = pd . DataFrame ( data )
# Write DataFrame to an Excel file
df . to_excel ( '/mnt/data/saved_data.xlsx' , index = False )
您可以根據條件過濾資料、新增列或轉換現有資料:
# Filter rows where age is greater than 28
filtered_df = df [ df [ 'Age' ] > 28 ]
# Add a new column
df [ 'Age Next Year' ] = df [ 'Age' ] + 1
# Sort data
sorted_df = df . sort_values ( by = 'Age' , ascending = False )
除了讀取和寫入 Excel 檔案之外,您還可以執行進階資料處理任務,例如建立資料透視表或合併多個 Excel 檔案。
import pandas as pd
# Load example data
df = pd . read_excel ( '/mnt/data/example.xlsx' )
# Create a pivot table
pivot_table = df . pivot_table ( index = 'Category' , values = 'Sales' , aggfunc = 'sum' )
# Display the pivot table
print ( pivot_table )
import pandas as pd
import glob
# Read all Excel files in the directory
files = glob . glob ( '/mnt/data/*.xlsx' )
# Merge data from all files
df_list = [ pd . read_excel ( file ) for file in files ]
merged_df = pd . concat ( df_list , ignore_index = True )
# Display the merged data
print ( merged_df . head ())
以下是一些常見問題及其解決方案:
如果您遇到其他問題,請在 GitHub 上提出問題或聯絡專案維護人員。
處理 Microsoft Word 文件涉及讀取、寫入和修改文件。以下是使用 Python 管理 Word 文件的方法:
要從 Word 文件中讀取文本,請使用python-docx
庫:
from docx import Document
# Load a Word document
doc = Document ( '/mnt/data/example.docx' )
# Read each paragraph
for para in doc . paragraphs :
print ( para . text )
若要建立並寫入 Word 文件:
from docx import Document
# Create a new Word document
doc = Document ()
doc . add_paragraph ( 'Hello, this is a test document.' )
# Save the document
doc . save ( '/mnt/data/new_example.docx' )
from docx import Document
# Create a new Word document
doc = Document ()
# Add a table with specified number of rows and columns
table = doc . add_table ( rows = 3 , cols = 3 )
# Add data to the table
data = [
[ "Header 1" , "Header 2" , "Header 3" ],
[ "Row 1, Col 1" , "Row 1, Col 2" , "Row 1, Col 3" ],
[ "Row 2, Col 1" , "Row 2, Col 2" , "Row 2, Col 3" ]
]
for row_index , row_data in enumerate ( data ):
row = table . rows [ row_index ]
for col_index , cell_data in enumerate ( row_data ):
row . cells [ col_index ]. text = cell_data
# Save the document
doc . save ( '/mnt/data/table_example.docx' )
from docx import Document
from docx . shared import Pt , RGBColor
# Load a Word document
doc = Document ( '/mnt/data/example.docx' )
# Add a paragraph with specific formatting
paragraph = doc . add_paragraph ()
run = paragraph . add_run ( 'This is a formatted text.' )
run . font . size = Pt ( 14 ) # Font size
run . font . bold = True # Bold text
run . font . color . rgb = RGBColor ( 255 , 0 , 0 ) # Red color text
# Save the document
doc . save ( '/mnt/data/formatted_text.docx' )
from docx import Document
from docx . shared import Inches
# Create a new Word document
doc = Document ()
# Add a paragraph
doc . add_paragraph ( 'Below is an image:' )
# Add an image to the document
doc . add_picture ( '/mnt/data/your_image.jpg' , width = Inches ( 4 ), height = Inches ( 3 ))
# Save the document
doc . save ( '/mnt/data/image_example.docx' )
from docx import Document
# Create a new Word document
doc = Document ()
# Add a header
header = doc . sections [ 0 ]. header
header_paragraph = header . paragraphs [ 0 ]
header_paragraph . text = "This is the header"
# Add a footer
footer = doc . sections [ 0 ]. footer
footer_paragraph = footer . paragraphs [ 0 ]
footer_paragraph . text = "This is the footer"
# Add some body text
doc . add_paragraph ( "This is the body text of the document." )
# Save the document
doc . save ( '/mnt/data/header_footer_example.docx' )
管理 PDF 文件通常涉及閱讀、提取文本,有時還涉及將其轉換為其他格式。以下是使用 Python 處理 PDF 文件的方法:
要從 PDF 文件中讀取和提取文本,通常使用PyPDF2
庫:
import PyPDF2
# Open a PDF file
with open ( '/mnt/data/example.pdf' , 'rb' ) as file :
pdf_reader = PyPDF2 . PdfReader ( file )
# Extract text from the first page
page = pdf_reader . pages [ 0 ]
text = page . extract_text ()
print ( text )
可以使用fpdf2
庫建立文字並將其寫入 PDF 文件:
from fpdf import FPDF
# Create instance of FPDF class
pdf = FPDF ()
# Add a page
pdf . add_page ()
# Set font
pdf . set_font ( "Arial" , size = 12 )
# Add a cell
pdf . cell ( 200 , 10 , txt = "Welcome to PDF handling with Python!" , ln = True , align = 'C' )
# Save the PDF to a file
pdf . output ( '/mnt/data/new_example.pdf' )
處理 PDF 文件通常涉及閱讀、提取文字、合併、拆分和修改文件。以下是一些使用Python的進階操作:
import PyPDF2
# List of PDF files to be merged
pdf_files = [ '/mnt/data/file1.pdf' , '/mnt/data/file2.pdf' , '/mnt/data/file3.pdf' ]
# Create a PDF merger object
pdf_merger = PyPDF2 . PdfMerger ()
# Append each PDF file
for pdf in pdf_files :
pdf_merger . append ( pdf )
# Write out the merged PDF
with open ( '/mnt/data/merged.pdf' , 'wb' ) as merged_pdf :
pdf_merger . write ( merged_pdf )
import PyPDF2
# Path to the PDF file
pdf_path = '/mnt/data/example.pdf'
# Create a PDF reader object
pdf_reader = PyPDF2 . PdfReader ( pdf_path )
# Split the PDF into separate pages
for page_num in range ( len ( pdf_reader . pages )):
pdf_writer = PyPDF2 . PdfWriter ()
pdf_writer . add_page ( pdf_reader . pages [ page_num ])
# Save each page as a separate PDF
output_path = f'/mnt/data/split_page_ { page_num + 1 } .pdf'
with open ( output_path , 'wb' ) as output_pdf :
pdf_writer . write ( output_pdf )
import PyPDF2
# Paths to the original PDF and the watermark PDF
original_pdf_path = '/mnt/data/original.pdf'
watermark_pdf_path = '/mnt/data/watermark.pdf'
# Create PDF reader objects
original_pdf = PyPDF2 . PdfReader ( original_pdf_path )
watermark_pdf = PyPDF2 . PdfReader ( watermark_pdf_path )
# Create a PDF writer object
pdf_writer = PyPDF2 . PdfWriter ()
# Apply the watermark to each page
for page_num in range ( len ( original_pdf . pages )):
original_page = original_pdf . pages [ page_num ]
watermark_page = watermark_pdf . pages [ 0 ]
original_page . merge_page ( watermark_page )
pdf_writer . add_page ( original_page )
# Save the watermarked PDF
with open ( '/mnt/data/watermarked.pdf' , 'wb' ) as watermarked_pdf :
pdf_writer . write ( watermarked_pdf )
import PyPDF2
# Path to the PDF file
pdf_path = '/mnt/data/example.pdf'
# Create a PDF reader object
pdf_reader = PyPDF2 . PdfReader ( pdf_path )
# Specify the range of pages to extract text from
start_page = 1
end_page = 3
# Extract text from the specified page range
extracted_text = ''
for page_num in range ( start_page - 1 , end_page ):
page = pdf_reader . pages [ page_num ]
extracted_text += page . extract_text ()
print ( extracted_text )
import PyPDF2
# Path to the PDF file
pdf_path = '/mnt/data/example.pdf'
# Create a PDF reader object
pdf_reader = PyPDF2 . PdfReader ( pdf_path )
pdf_writer = PyPDF2 . PdfWriter ()
# Copy all pages to the writer object
for page_num in range ( len ( pdf_reader . pages )):
pdf_writer . add_page ( pdf_reader . pages [ page_num ])
# Add metadata
metadata = {
'/Title' : 'Example PDF' ,
'/Author' : 'Your Name' ,
'/Subject' : 'Example Subject' ,
'/Keywords' : 'PDF, example, metadata'
}
pdf_writer . add_metadata ( metadata )
# Save the PDF with metadata
with open ( '/mnt/data/metadata_example.pdf' , 'wb' ) as metadata_pdf :
pdf_writer . write ( metadata_pdf )
歡迎貢獻!請隨時提交拉取請求。
如果您欣賞我的工作,請考慮支持我: