반응형
반응형

파일 선택 창을 띄워 파일을 선택하고, 선택한 파일을 읽어서 내용을 출력하는 PyQt5 프로그램입니다. 파일 선택 창은 QFileDialog를 사용합니다.

선택한 파일이 엑셀 파일(.xlsx, .xls)인 경우, 엑셀 내용을 시트별로 읽어와 화면에 출력하고, 텍스트 파일인 경우 텍스트 내용을 그대로 보여주는 PyQt5 프로그램입니다.

엑셀 파일 처리를 위해 openpyxl 또는 pandas 라이브러리를 사용할 수 있습니다. 여기서는 pandas를 이용합니다.

 

 

 

import sys
import os
import pandas as pd
from PyQt5.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QPushButton, QLabel, QFileDialog, QTextEdit
)


class FileHandlerApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # 윈도우 설정
        self.setWindowTitle("File Handler App")
        self.setGeometry(100, 100, 800, 600)

        # 레이아웃 설정
        layout = QVBoxLayout()

        # 파일 선택 버튼
        self.select_button = QPushButton("Select File", self)
        self.select_button.clicked.connect(self.select_file)
        layout.addWidget(self.select_button)

        # 파일 경로 표시
        self.file_path_label = QLabel("No file selected", self)
        layout.addWidget(self.file_path_label)

        # 파일 내용 표시
        self.file_content = QTextEdit(self)
        self.file_content.setReadOnly(True)
        layout.addWidget(self.file_content)

        # 레이아웃 적용
        self.setLayout(layout)

    def select_file(self):
        # 파일 선택 창 띄우기
        options = QFileDialog.Options()
        options |= QFileDialog.ReadOnly
        file_path, _ = QFileDialog.getOpenFileName(
            self, "Select File", "", "All Files (*);;Excel Files (*.xlsx *.xls);;Text Files (*.txt)", options=options
        )

        if file_path:
            # 선택한 파일 경로 표시
            self.file_path_label.setText(f"Selected File: {file_path}")

            # 파일 확장자 확인
            _, file_extension = os.path.splitext(file_path)

            # 파일 처리
            if file_extension in [".xlsx", ".xls"]:
                self.read_excel(file_path)
            elif file_extension == ".txt":
                self.read_text(file_path)
            else:
                self.file_content.setText("Unsupported file type. Please select an Excel or text file.")

    def read_text(self, file_path):
        """텍스트 파일을 읽어와 화면에 표시"""
        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                content = file.read()
                self.file_content.setText(content)
        except Exception as e:
            self.file_content.setText(f"Error reading file: {str(e)}")

    def read_excel(self, file_path):
        """엑셀 파일을 읽어와 화면에 표시"""
        try:
            excel_data = pd.ExcelFile(file_path)  # 엑셀 파일 읽기
            content = "Excel File Content:\n\n"

            # 시트별로 데이터 읽기
            for sheet_name in excel_data.sheet_names:
                content += f"Sheet: {sheet_name}\n"
                sheet_data = excel_data.parse(sheet_name).head(10)  # 각 시트의 첫 10행 읽기
                content += sheet_data.to_string(index=False)
                content += "\n\n"

            self.file_content.setText(content)
        except Exception as e:
            self.file_content.setText(f"Error reading Excel file: {str(e)}")


# 프로그램 실행
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = FileHandlerApp()
    window.show()
    sys.exit(app.exec_())
반응형
반응형

[python] Django 설치

 conda create -n p_django python=3.11

 

 

Django 설치 확인

 python -m django --version

반응형
반응형

 

프로젝트를 다른 시스템(예: 동료 개발자의 컴퓨터 또는 배포 서버)으로 옮길 때, 동일한 파이썬 버전과 패키지를 정확히 맞춰야 하는 번거로움이 있습니다. 가상환경 내 설치된 패키지 목록을 requirements.txt로 저장하고, 이를 다른 환경에서 설치하면 동일한 실행 환경을 쉽게 재현할 수 있습니다.

현재 가상환경 패키지 목록 저장하려면 다음과 같이 실행합니다.

pip freeze > requirements.txt

다른 환경에서 패키지를 설치하려면 다음과 같이 실행합니다.

pip install -r requirements.txt

 

 

반응형
반응형

[python] Scatter plot animated using python, ffmpeg

 

""" 
An animated scatter plot can be created using Python's matplotlib library with its animation module. 
Here's an example of how to create an animated scatter plot, where points move dynamically over time.
"""

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# Generate random initial data for the scatter plot
num_points = 50
x_data = np.random.rand(num_points)
y_data = np.random.rand(num_points)
colors = np.random.rand(num_points)
sizes = np.random.rand(num_points) * 100

# Function to update scatter plot
def update(frame):
    global x_data, y_data
    x_data += (np.random.rand(num_points) - 0.5) * 0.1  # Randomly move x
    y_data += (np.random.rand(num_points) - 0.5) * 0.1  # Randomly move y
    scatter.set_offsets(np.c_[x_data, y_data])  # Update positions
    scatter.set_sizes(np.random.rand(num_points) * 100)  # Update sizes
    scatter.set_array(np.random.rand(num_points))  # Update colors
    return scatter,

# Create the figure and scatter plot
fig, ax = plt.subplots()
scatter = ax.scatter(x_data, y_data, c=colors, s=sizes, cmap='viridis', alpha=0.6)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_title("Animated Scatter Plot")

# Create animation
ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)

# Show the animation
plt.show()

import matplotlib.animation as animation
animation.FFMpegWriter = animation.writers['ffmpeg']

""" 
Install FFmpeg: FFmpeg is required to save animations in video formats like .mp4. Install it as follows:

Windows:

Download the FFmpeg executable from https://ffmpeg.org/download.html.
Add the bin folder to your system’s PATH environment variable.

1.EXE  파일 다운받아서  *.7z 파일 다운로드. 

2.압축 풀고,  시스템 환경 변수에 추가. 

3.  ffmpeg -version  으로 실행되는지 확인 

"""

ani.save("animated_scatter.mp4", writer="ffmpeg", fps=30)  # Save as MP4

반응형
반응형
""" 
정렬 알고리즘 실행 시 비용 계산은 보통 실행 시간(시간 복잡도)이나 작업 횟수를 측정하여 이뤄집니다. 

이를 위해 Python에서 time 모듈이나 timeit 모듈을 사용할 수 있습니다. 

시간 복잡도에 따른 차이

1.퀵 정렬:
    평균 시간 복잡도 𝑂(𝑛log⁡𝑛)O(nlogn).
    큰 데이터셋에서도 효율적으로 작동.

2.버블 정렬:
    최악 및 평균 시간 복잡도 𝑂(𝑛2)O(n 2 ).
    작은 데이터셋에서는 괜찮지만, 데이터 크기가 클수록 비효율적.
    
"""
import time  # 실행 시간 측정을 위한 모듈

# 퀵 정렬 알고리즘
def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quick_sort(left) + middle + quick_sort(right)

# 버블 정렬 알고리즘
def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr

# 테스트 데이터 생성
import random
array_size = 1000  # 데이터 크기
test_array = random.sample(range(1, 10000), array_size)


print(f" test_array : {test_array} \n\n\n")

# 퀵 정렬 실행 시간 측정
start_time = time.time()
quick_sort(test_array.copy())
end_time = time.time()
print(f"퀵 정렬 실행 시간: {end_time - start_time:.5f}초")

# 버블 정렬 실행 시간 측정
start_time = time.time()
bubble_sort(test_array.copy())
end_time = time.time()
print(f"버블 정렬 실행 시간: {end_time - start_time:.5f}초")


# 병합 정렬 알고리즘
def merge_sort(arr):
    if len(arr) <= 1:
        return arr
    mid = len(arr) // 2
    left = merge_sort(arr[:mid])
    right = merge_sort(arr[mid:])
    return merge(left, right)

def merge(left, right):
    result = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    result.extend(left[i:])
    result.extend(right[j:])
    return result

# 병합 정렬 실행 시간 측정
start_time = time.time()
merge_sort(test_array.copy())
end_time = time.time()
print(f"병합 정렬 실행 시간: {end_time - start_time:.5f}초")

[python] 정렬 알고리즘 실행 시 비용 계산은 보통 실행 시간(시간 복잡도)이나 작업 횟수를 측정

 

 

 

반응형
반응형

[python] Happy New year 2025 loop

import time
from random import randint


for i in range(1,85):
    print('')

space = ''


for i in range(1,1000):
    count = randint(1, 100)
    while(count > 0):
        space += ' '
        count -= 1

    if(i%10==0):
        print(space + 'Happy New Year 2025🎉')
    elif(i%9 == 0):
        print(space + "🪅")
    elif(i%5==0):
        print(space +"🎈")
    elif(i%8==0):
        print(space + "🎈")
    elif(i%7==0):
        print(space + "🍁")
    elif(i%6==0):
        print(space + "❤️")
    else:
        print(space + "🔸")

    space = ''
    time.sleep(0.2)
 
반응형

+ Recent posts