# Spiral Web using Matplotlib and NumPy
import numpy as np
import matplotlib.pyplot as plt
def draw_spiral_web():
# Parameters
num_lines = 50 # Number of radial lines
num_circles = 10 # Number of concentric circles
max_radius = 10 # Maximum radius of the spiral web
# Generate theta for radial lines (angle from 0 to 2*pi)
theta = np.linspace(0, 2 * np.pi, num_lines, endpoint=False)
# Generate radii for concentric circles
radii = np.linspace(0, max_radius, num_circles)
# Create a figure
fig, ax = plt.subplots(figsize=(6, 6), subplot_kw={'projection': 'polar'})
ax.set_facecolor('black') # Set background color to black
ax.set_xticks([]) # Remove angular ticks
ax.set_yticks([]) # Remove radial ticks
# Draw radial lines
for t in theta:
ax.plot([t, t], [0, max_radius], color='cyan', linewidth=0.7)
# Draw concentric circles
for r in radii:
ax.plot(np.linspace(0, 2 * np.pi, 100), [r] * 100, color='cyan', linewidth=0.7)
# Add a spiral
spiral_theta = np.linspace(0, 4 * np.pi, 500) # 2 full rotations
spiral_r = np.linspace(0, max_radius, 500)
ax.plot(spiral_theta, spiral_r, color='yellow', linewidth=1)
# Set aspect ratio and display the plot
ax.set_ylim(0, max_radius)
plt.show()
# Call the function to draw the spiral web
if __name__ == "__main__":
draw_spiral_web()
사용자가 초 단위로 시간을 입력하면 카운트다운을 실행하는 간단한 Python 프로그램입니다.
time 모듈을 사용하여 매초 업데이트하며, 남은 시간을 출력합니다.
# 사용자가 초 단위로 시간을 입력하면 카운트다운을 실행하는 간단한 Python 프로그램입니다.
# time 모듈을 사용하여 매초 업데이트하며, 남은 시간을 출력합니다.
import time
def countdown(seconds):
"""
Counts down from the given number of seconds.
:param seconds: Total seconds to count down
"""
try:
while seconds >= 0:
mins, secs = divmod(seconds, 60)
timer = f"{mins:02}:{secs:02}" # Format as MM:SS
# 매초마다 동일한 줄에 시간을 출력.
# end="\r"를 사용하여 이전 출력 내용을 덮어씁니다.
print(timer, end="\r") # Print on the same line
time.sleep(1) # Wait for 1 second
seconds -= 1
print("Time's up!")
except KeyboardInterrupt:
print("\nCountdown stopped.")
# Example: Enter seconds to countdown
if __name__ == "__main__":
try:
user_input = int(input("Enter the number of seconds for countdown: "))
countdown(user_input)
except ValueError:
print("Please enter a valid integer.")
Python을 사용하여 Wi-Fi QR 코드를 생성하려면 qrcode 및 Pillow 라이브러리를 활용할 수 있습니다. Wi-Fi QR 코드의 데이터 형식은 다음과 같습니다:
import qrcode
from PIL import Image
def generate_wifi_qrcode(ssid, password, encryption="WPA", hidden=False, output_file="wifi_qrcode.png"):
"""
Generates a Wi-Fi QR code and saves it as an image.
:param ssid: The Wi-Fi network name (SSID)
:param password: The Wi-Fi password
:param encryption: Encryption type ('WPA', 'WEP', or 'nopass')
:param hidden: Whether the network is hidden (True/False)
:param output_file: Name of the output image file
"""
# Format Wi-Fi QR code data
wifi_data = f"WIFI:S:{ssid};T:{encryption};P:{password};H:{'true' if hidden else 'false'};;"
# Generate QR code
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(wifi_data)
qr.make(fit=True)
# Create and save the QR code image
img = qr.make_image(fill_color="black", back_color="white")
img.save(output_file)
print(f"Wi-Fi QR code saved as {output_file}")
# Open and show the image
img.show()
# Example usage
generate_wifi_qrcode(
ssid="MyWiFiNetwork",
password="MySecurePassword",
encryption="WPA", # WPA/WEP/nopass
hidden=False, # Hidden network? True/False
output_file="wifi_qrcode.png"
)
"""
Sunburst Chart는 계층적 데이터를 시각화하는 데 사용되는 원형 차트입니다.
데이터의 루트는 중앙에 있고,
계층적으로 데이터를 표현하며, 내부에서 외부로 확장됩니다.
각 섹션은 데이터를 크기별로 구분하여 보여줍니다.
"""
import plotly.express as px
from PIL import Image
# 계층적 데이터 정의
data = dict(
labels=["Root", "Child 1", "Child 2", "Grandchild 1", "Grandchild 2", "Grandchild 3"],
parents=["", "Root", "Root", "Child 1", "Child 1", "Child 2"],
values=[10, 5, 5, 2, 3, 5]
)
# Sunburst Chart 생성
fig = px.sunburst(
data,
names='labels',
parents='parents',
values='values',
title="Sunburst Chart Example"
)
# fig.show()
# Sunburst Chart를 이미지로 저장
image_path = "sunburst_chart_001.png"
fig.write_image(image_path, width=800, height=600)
print(f"Sunburst chart saved as '{image_path}'")
# 저장된 이미지 출력
image = Image.open(image_path)
image.show() # 기본 이미지 뷰어로 열기
This article explains the new features inPython 3.13, compared to3.12. Python 3.13 was released on October 7, 2024, marking a significant advancement for the language. Many of the most impactful changes occur behind the scenes, so they may take time to notice.
Python 3.13 is setting the stage for future enhancements, particularly in terms ofperformance improvements. For full details, see thechangelog.
Python 3.13 is the latest stable release of the Python programming language, with a mix of changes to the language, the implementation and the standard library. The biggest changes include a newinteractive interpreter, experimental support for running in afree-threaded mode(PEP 703), and aJust-In-Time compiler(PEP 744).
Error messages continue to improve, with tracebacks now highlighted in color by default. Thelocals()builtin now hasdefined semanticsfor changing returning mapping, and type parameters now support values.
The library changes contain removal of deprecated APIs and modules, as well as the usual improvements in user-friendliness and correctness. Several legacy standard library modules have nowbeen removedfollowing their deprecation in Python 3.11 (PEP 594).
Here is a list of major features and improved modules.
·Improved REPL
· Free Threading Cpython
· An Experimental just-in-time (JIT)
· Improved Error Messages
· Copy’s Replace
· Support for Mobile Platforms
Improved REPL
Python now uses a newinteractiveshell by default, based on code from thePyPy project. When the user starts theREPLfrom an interactive terminal, the following new features are now supported:
Multiline editing with history preservation.
Direct support for REPL-specific commands like help, exit, and quit, without the need to call them as functions.
Interactive help browsing using F1 with a separate command history.
History browsing using F2 that skips output as well as the>>>and…prompts.
“Paste mode” with F3 that makes pasting larger blocks of code easier (press F3 again to return to the regular prompt).
Free Threading Cpython
CPython now has experimental support for running in a free-threaded mode, with theglobal interpreter lock(GIL) disabled. This is an experimental feature and therefore is not enabled by default. The free-threaded mode requires a different executable, usually called python3.13t or python3.13t.exe. Pre-built binaries marked asfree-threadedcan be installed as part of the officialWindowsandmacOSinstallers, or CPython can be built from source with the— disable-giloption.
An Experimental just-in-time (JIT)
When CPython is configured and built using the — enable-experimental-jit option, a just-in-time (JIT) compiler is added which may speed up some Python programs. On Windows, use PCbuild/build.bat — experimental-jit to enable the JIT or — experimental-jit-interpreter to enable the Tier 2 interpreter. Build requirements and further supporting informationare contained atTools/jit/README.md.
Improved Error Messages
The interpreter now uses color by default when displaying tracebacks in the terminal. This featurecan be controlledvia the newPYTHON_COLORSenvironment variable as well as the canonicalNO_COLORandFORCE_COLORenvironment variables. (Contributed by Pablo Galindo Salgado ingh-112730.)
The error message now tries to suggest the correct keyword argument when an incorrect keyword argument is passed to a function.
# Incorrect usage of the built-in sorted() function
sorted([3, 1, 2], reversed=True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sorted([3, 1, 2], reversed=True)
~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
TypeError: sorted() got an unexpected keyword argument 'reversed'. Did you mean 'reverse'?
Copy’s Replace
The newreplace()function and thereplace protocolmake creating modified copies of objects much simpler. This is especially useful when working with immutable objects. The following types support thereplace()function and implement the replace protocol:
PEP 730: iOS is now aPEP 11supported platform, with the arm64-apple-ios and arm64-apple-ios-simulator targets at tier 3 (iPhone and iPad devices released after 2013 and the Xcode iOS simulator running on Apple silicon hardware, respectively). x86_64-apple-ios-simulator (the Xcode iOS simulator running on older x86_64 hardware) is not a tier 3 supported platform, but will have best-effort support. (PEP written and implementation contributed by Russell Keith-Magee ingh-114099.)
PEP 738: Android is now aPEP 11supported platform, with the aarch64-linux-android and x86_64-linux-android targets at tier 3. The 32-bit targets arm-linux-androideabi and i686-linux-android are not tier 3 supported platforms, but will have best-effort support. (PEP written and implementation contributed by Malcolm Smith ingh-116622.)
PyQt5와 requests 및 BeautifulSoup를 이용해 URL을 입력하고, 해당 웹 페이지의 내용을 크롤링하여 보여주는 기본 프로그램.
입력한 URL의 HTML 내용과 크롤링된 특정 텍스트 내용을 보여주는 두 개의 영역
import sys
import requests
from bs4 import BeautifulSoup
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton, QScrollArea, QTextBrowser, QTextEdit
from PyQt5.QtCore import Qt
class WebCrawlerApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# 창 설정
self.setWindowTitle("URL Web Crawler")
self.setGeometry(300, 300, 800, 600)
# 메인 레이아웃 설정
layout = QVBoxLayout()
# URL 입력창 및 버튼 추가
self.url_input = QLineEdit(self)
self.url_input.setPlaceholderText("Enter URL here...")
layout.addWidget(self.url_input)
self.submit_button = QPushButton("Submit", self)
self.submit_button.clicked.connect(self.fetch_web_content)
layout.addWidget(self.submit_button)
# HTML 내용 표시 (링크 지원을 위해 QTextBrowser 사용)
self.html_label = QLabel("Page HTML Content:")
layout.addWidget(self.html_label)
self.html_content = QTextBrowser(self)
self.html_content.setOpenExternalLinks(False) # QTextBrowser 내부에서 링크 클릭 이벤트를 처리
self.html_content.anchorClicked.connect(self.handle_link_click)
html_scroll = QScrollArea(self)
html_scroll.setWidgetResizable(True)
html_scroll.setWidget(self.html_content)
layout.addWidget(html_scroll)
# 크롤링된 내용을 보여줄 텍스트 창
self.crawl_label = QLabel("Crawled Data:")
layout.addWidget(self.crawl_label)
self.crawled_content = QTextEdit(self)
self.crawled_content.setReadOnly(True)
crawl_scroll = QScrollArea(self)
crawl_scroll.setWidgetResizable(True)
crawl_scroll.setWidget(self.crawled_content)
layout.addWidget(crawl_scroll)
# 레이아웃 설정
self.setLayout(layout)
def fetch_web_content(self):
# URL 가져오기
url = self.url_input.text().strip()
if not url:
self.html_content.setText("Please enter a valid URL.")
return
try:
# 웹 페이지 요청 및 파싱
response = requests.get(url)
response.raise_for_status()
html_text = response.text
# HTML 내용을 보여줌
self.html_content.setHtml(html_text)
# BeautifulSoup으로 HTML 파싱
soup = BeautifulSoup(html_text, 'html.parser')
# 특정 태그 내용 크롤링 예시 (모든 <p> 태그 내용)
paragraphs = soup.find_all('p')
crawled_data = "\n\n".join([p.get_text(strip=True) for p in paragraphs])
# 크롤링된 내용 표시
if crawled_data:
self.crawled_content.setText(crawled_data)
else:
self.crawled_content.setText("No <p> tags found on the page.")
except requests.exceptions.RequestException as e:
self.html_content.setText(f"Error fetching the URL: {e}")
self.crawled_content.setText("")
def handle_link_click(self, url):
# 링크를 클릭하면 URL 입력창에 설정하고 자동으로 Submit
self.url_input.setText(url.toString())
self.fetch_web_content()
# 애플리케이션 실행
if __name__ == "__main__":
app = QApplication(sys.argv)
window = WebCrawlerApp()
window.show()
sys.exit(app.exec_())