반응형

[python] pip install prettytable, 표 형태로 데이터를 보여준다. 

 

pip install prettytable

 

 

https://pypi.org/project/prettytable/

 

prettytable

A simple Python library for easily displaying tabular data in a visually appealing ASCII table format

pypi.org

시각적으로 매력적인 ASCII 테이블 형식으로 표 형식의 데이터를 쉽게 표시하기 위한 간단한 Python 라이브러리

A simple Python library for easily displaying tabular data in a visually appealing ASCII table format

 

from prettytable import PrettyTable

# Create a PrettyTable object
table = PrettyTable()

# Define the table's columns
table.field_names = ["Name", "Age", "City"]

# Add rows to the table
table.add_row(["Alice", 30, "New York"])
table.add_row(["Bob", 25, "Los Angeles"])
table.add_row(["Charlie", 35, "Chicago"])

# Print the table
print(table)

 

# HTML 형식으로 테이블 표시


# HTML 형식으로 테이블 표시
# PrettyTable은 HTML 형식으로 테이블을 인쇄합니다 <table>. ASCII 형식과 마찬가지로 실제로 문자열 표현을 얻을 수 있습니다 
# get_html_string(). . HTML 인쇄는 ASCII 인쇄 와 동일한 방식으로 fields, start, 및 인수를 지원합니다.

print('\n\n',table.get_html_string(attributes={"id":"my_table", "class":"red_table"}))

반응형
반응형

[python] 엑셀 읽고 쓰기 

 

https://pypi.org/project/openpyxl/

 

openpyxl

A Python library to read/write Excel 2010 xlsx/xlsm files

pypi.org

 

pip install openpyxl

 

반응형
반응형

[python] 한글 자음, 모음, 초성 추출하기 

 

# pip install jamotools 
# https://pypi.org/project/jamotools/
# A library for Korean Jamo split and vectorize. 
#
# 음절 분할 및 jamos를 음절에 결합하는 API는 hangul-utils 를 기반으로 합니다 .
# 
# Split_syllables : 음절 문자열을 jamos 문자열로 변환하고 유니코드 유형을 변환하도록 선택할 수 있습니다.
# Join_jamos : jamos 문자열을 음절 문자열로 변환합니다.
# Normalize_to_compat_jamo : jamos 문자열을 한글 호환성 Jamo 문자열로 정규화합니다 .
import jamotools

print(jamotools.split_syllable_char(u"안"))
#('ㅇ', 'ㅏ', 'ㄴ')

print(jamotools.split_syllables(u"안녕하세요"))
# ㅇㅏㄴㄴㅕㅇㅎㅏㅅㅔㅇㅛ


sentence = u"앞 집 팥죽은 붉은 팥 풋팥죽이고, 뒷집 콩죽은 햇콩 단콩 콩죽.우리 집  깨죽은 검은 깨 깨죽인데 사람들은 햇콩 단콩 콩죽 깨죽 죽먹기를 싫어하더라."
s = jamotools.split_syllables(sentence)
print(s, '\n')

""" ㅇㅏㅍ ㅈㅣㅂ ㅍㅏㅌㅈㅜㄱㅇㅡㄴ ㅂㅜㄺㅇㅡㄴ ㅍㅏㅌ ㅍㅜㅅㅍㅏㅌㅈㅜㄱㅇㅣㄱㅗ,
ㄷㅟㅅㅈㅣㅂ ㅋㅗㅇㅈㅜㄱㅇㅡㄴ ㅎㅐㅅㅋㅗㅇ ㄷㅏㄴㅋㅗㅇ ㅋㅗㅇㅈㅜㄱ.ㅇㅜㄹㅣ
ㅈㅣㅂ ㄲㅐㅈㅜㄱㅇㅡㄴ ㄱㅓㅁㅇㅡㄴ ㄲㅐ ㄲㅐㅈㅜㄱㅇㅣㄴㄷㅔ ㅅㅏㄹㅏㅁㄷㅡㄹㅇㅡㄴ
ㅎㅐㅅㅋㅗㅇ ㄷㅏㄴㅋㅗㅇ ㅋㅗㅇㅈㅜㄱ ㄲㅐㅈㅜㄱ ㅈㅜㄱㅁㅓㄱㄱㅣㄹㅡㄹ
ㅅㅣㅀㅇㅓㅎㅏㄷㅓㄹㅏ. """

sentence2 = jamotools.join_jamos(s)
print(sentence2)
""" 앞 집 팥죽은 붉은 팥 풋팥죽이고, 뒷집 콩죽은 햇콩 단콩 콩죽.우리 집 깨죽은 검은 깨
깨죽인데 사람들은 햇콩 단콩 콩죽 깨죽 죽먹기를 싫어하더라. """

print(sentence == sentence2)
# True


# 자음만 추출
def extract_vowels(text):
    vowels = set(['ㅏ', 'ㅑ', 'ㅓ', 'ㅕ', 'ㅗ', 'ㅛ', 'ㅜ', 'ㅠ', 'ㅡ', 'ㅣ', 'ㅐ', 'ㅒ', 'ㅔ', 'ㅖ', 'ㅘ', 'ㅙ', 'ㅚ', 'ㅝ', 'ㅞ', 'ㅟ', 'ㅢ'])
    result = ''
    for char in text:
        if '가' <= char <= '힣':  # Check if the character is Hangul
            syllables = jamotools.split_syllables(char)
            for syllable in syllables:
                if syllable in vowels:
                    result += syllable
    return result

sentence = u"앞 집 팥죽은 붉은 팥 풋팥죽이고, 뒷집 콩죽은 햇콩 단콩 콩죽.우리 집  깨죽은 검은 깨 깨죽인데 사람들은 햇콩 단콩 콩죽 깨죽 죽먹기를 싫어하더라."
vowels_only = extract_vowels(sentence)
print(vowels_only)
# ㅏㅣㅏㅜㅡㅜㅡㅏㅜㅏㅜㅣㅗㅟㅣㅗㅜㅡㅐㅗㅏㅗㅗㅜㅜㅣㅣㅐㅜㅡㅓㅡㅐㅐㅜㅣㅔㅏㅏㅡㅡㅐㅗㅏㅗㅗㅜㅐㅜㅜㅓㅣㅡㅣㅓㅏㅓㅏ


# 모음만 추출 
def extract_consonants(text):
    consonants = set(['ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ', 'ㄹ', 'ㅁ', 'ㅂ', 'ㅃ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ'])
    result = ''
    for char in text:
        if '가' <= char <= '힣':  # Check if the character is Hangul
            syllables = jamotools.split_syllables(char)
            for syllable in syllables:
                if syllable in consonants:
                    result += syllable
    return result

sentence = u"앞 집 팥죽은 붉은 팥 풋팥죽이고, 뒷집 콩죽은 햇콩 단콩 콩죽.우리 집  깨죽은 검은 깨 깨죽인데 사람들은 햇콩 단콩 콩죽 깨죽 죽먹기를 싫어하더라."
consonants_only = extract_consonants(sentence)
print(consonants_only)
# ㅇㅍㅈㅂㅍㅌㅈㄱㅇㄴㅂㅇㄴㅍㅌㅍㅅㅍㅌㅈㄱㅇㄱㄷㅅㅈㅂㅋㅇㅈㄱㅇㄴㅎㅅㅋㅇㄷㄴㅋㅇㅋㅇㅈㄱㅇㄹㅈㅂㄲㅈㄱㅇㄴㄱㅁㅇㄴㄲㄲㅈㄱㅇㄴㄷㅅㄹㅁㄷㄹㅇㄴㅎㅅㅋㅇㄷㄴㅋㅇㅋㅇㅈㄱㄲㅈㄱㅈㄱㅁㄱㄱㄹㄹㅅㅇㅎㄷㄹ


# 초성만 추출 
def extract_initial_consonants(text):
    result = ''
    for char in text:
        if '가' <= char <= '힣':  # Check if the character is Hangul
            initial_consonant = jamotools.split_syllable_char(char)[0]
            result += initial_consonant
    return result

sentence = u"앞 집 팥죽은 붉은 팥 풋팥죽이고, 뒷집 콩죽은 햇콩 단콩 콩죽.우리 집  깨죽은 검은 깨 깨죽인데 사람들은 햇콩 단콩 콩죽 깨죽 죽먹기를 싫어하더라."
initial_consonants_only = extract_initial_consonants(sentence)
print(initial_consonants_only)
반응형
반응형

Matplotlib Tutorial - 파이썬으로 데이터 시각화하기

 

https://wikidocs.net/book/5011

 

Matplotlib Tutorial - 파이썬으로 데이터 시각화하기

## 도서 소개 - 이 책은 파이썬의 대표적인 데이터 시각화 라이브러리인 Matplotlib의 사용법을 소개합니다. - 30여 개 이상의 다양한 주제에 대해 100개…

wikidocs.net

Matplotlib 데이터 시각화와 2D 그래프 플롯에 사용되는 파이썬 라이브러리입니다.

Matplotlib을 이용하면 아래 그림과 같이 다양한 유형의 그래프를 간편하게 그릴 수 있습니다.

 

 

Matplotlib의 간단한 사용법을 소개하고, 예제와 함께 다양한 그래프를 그려봅니다.

예제들은 Matplotlib 공식 홈페이지를 참고해서 만들었습니다.

순서는 아래와 같습니다.

 

Contents

00. Matplotlib 설치하기
01. Matplotlib 기본 사용
02. Matplotlib 숫자 입력하기
03. Matplotlib 축 레이블 설정하기
04. Matplotlib 범례 표시하기
05. Matplotlib 축 범위 지정하기
06. Matplotlib 선 종류 지정하기
07. Matplotlib 마커 지정하기
08. Matplotlib 색상 지정하기
09. Matplotlib 그래프 영역 채우기
10. Matplotlib 축 스케일 지정하기
11. Matplotlib 여러 곡선 그리기
12. Matplotlib 그리드 설정하기
13. Matplotlib 눈금 표시하기
14. Matplotlib 타이틀 설정하기
15. Matplotlib 수평선/수직선 표시하기
16. Matplotlib 막대 그래프 그리기
17. Matplotlib 수평 막대 그래프 그리기
18. Matplotlib 산점도 그리기
19. Matplotlib 3차원 산점도 그리기
20. Matplotlib 히스토그램 그리기
21. Matplotlib 에러바 그리기
22. Matplotlib 파이 차트 그리기
23. Matplotlib 히트맵 그리기
24. Matplotlib 여러 개의 그래프 그리기
25. Matplotlib 컬러맵 설정하기
26. Matplotlib 텍스트 삽입하기
27. Matplotlib 수학적 표현 사용하기
28. Matplotlib 그래프 스타일 설정하기
29. Matplotlib 이미지 저장하기
30. Matplotlib 객체 지향 인터페이스 1
31. Matplotlib 객체 지향 인터페이스 2
32. Matplotlib 축 위치 조절하기
33. Matplotlib 이중 Y축 표시하기
34. Matplotlib 두 종류의 그래프 그리기
35. Matplotlib 박스 플롯 그리기
36. Matplotlib 바이올린 플롯 그리기
37. Matplotlib 다양한 도형 삽입하기
38. Matplotlib 다양한 패턴 채우기

 

반응형
반응형

 

The Go programming language enters the top 10

 

TIOBE Index for February 2024

 

https://www.tiobe.com/tiobe-index/

 

TIOBE Index - TIOBE

Home » TIOBE Index TIOBE Index for February 2024 February Headline: The Go programming language enters the top 10 This month, Go entered the TIOBE index top 10 at position 8. This is the highest position Go has ever had. When it was launched by Google in

www.tiobe.com

 

반응형
반응형
1. Pandas

Pandas is a software library written for the python programming language for data manipulation and analysis.

Pandas is well suited for many different kinds of data:
  • Tabular data with heterogeneously-types columns.
  • Ordered and unordered time series data.
  • Arbitrary matrix data with row and column labels.
  • Any other form of observational / statistical data sets.
 The data actually need not be labeled at all to be placed into a pandas data structure.

2. NumPy

Numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays.



3. Matplotlib

Matplotlib is a Python package used for 2D graphics.
  • Bar graph
  • Histograms
  • Scatter Plot
  • Pie Plot
  • Hexagonal Bin Plot
  • Area Plot

 


4. Selenium

The selenium package is used to automate web browser interaction from Python.


5. OpenCV

OpenCV- Python is a library of Python designed to solve computer vision problems.


6. SciPy

Scipy is a free and open-source Python library used for scientific computing and technical computing.


7. Scikit-Learn

Scikit-learn (formerly scikits.learn) is a free software machine learning library for the Python programming language. It features various classification, regression and clustering algorithms.


8.  PySpark

The Spark Python API (PySpark) exposes the Spark programming model to Python.



9. Django

Diango is a Python web framework. A framework provides a structure and common methods to make the life of a web application developer much easier for building flexible, scalable and maintainable web applications

  • Django is a high-level and has a MVC-MVT styled architecture.
  • Django web framework is written on quick and powerful Python language.
  • Django has a open-source collection of libraries for building a fully functioning web application.


10. Tensor Flow

TensorFlow is a Python library used to implement deep networks. In TensorFlow, computation is approached as a dataflow graph.


반응형
반응형

[python] pdf to png, 해상도 높게 저장하기 

 

import fitz  # PyMuPDF

def pdf_to_png(pdf_file, output_folder, dpi=300):
    # Open the PDF file
    pdf_document = fitz.open(pdf_file)
    
    for page_number in range(pdf_document.page_count):
        # Get the page
        page = pdf_document[page_number]
        
        # Set the resolution (DPI)
        zoom = dpi / 72.0
        mat = fitz.Matrix(zoom, zoom)
        image = page.get_pixmap(matrix=mat)
        
        # Save the image as a PNG file
        image.save(f"{output_folder}/page_{page_number + 1}.png", "png")

    # Close the PDF file
    pdf_document.close()

if __name__ == "__main__":
    input_pdf = "input.pdf"  # Replace with your PDF file path
    output_folder = "output_images"  # Replace with your output folder
    dpi = 600  # Adjust DPI as needed
    
    pdf_to_png(input_pdf, output_folder, dpi)
반응형

'프로그래밍 > Python' 카테고리의 다른 글

[python] PyAudio  (0) 2023.10.20
[Python] savefig 0.0.4  (0) 2023.10.17
[python] matrix 3.0.0  (0) 2023.10.04
[python] 알고리즘 - 탐색  (0) 2023.09.27
[python] 알고리즘 - 정렬  (0) 2023.09.27
반응형

[python] sudoku 만들기 - 랜덤 문제 

#sudoku puzzle create using python chatGPT
import random

def generate_solved_sudoku():
    base  = 3
    side  = base*base
    # pattern for a baseline valid solution
    def pattern(r,c): return (base*(r%base)+r//base+c)%side

    # randomize rows, columns and numbers (of valid base pattern)
    def shuffle(s): return random.sample(s,len(s)) 
    rBase = range(base) 
    rows  = [ g*base + r for g in shuffle(rBase) for r in shuffle(rBase) ] 
    cols  = [ g*base + c for g in shuffle(rBase) for c in shuffle(rBase) ]
    nums  = shuffle(range(1,base*base+1))

    # produce board using randomized baseline pattern
    board = [ [nums[pattern(r,c)] for c in cols] for r in rows ]
    
    return board

def print_sudoku(board):
    for i in range(9):
        if i % 3 == 0 and i != 0:
            print("- - - - - - - - - - - -")
        for j in range(9):
            if j % 3 == 0 and j != 0:
                print("|", end=" ")
            print(board[i][j], end=" ")
        print()

def remove_numbers(board, difficulty_level):
    """
    Remove numbers from the solved Sudoku grid based on the difficulty level.
    """
    if difficulty_level == 'easy':
        num_to_remove = 30  # Easy: 30 numbers removed
    elif difficulty_level == 'medium':
        num_to_remove = 40  # Medium: 40 numbers removed
    else:
        num_to_remove = 50  # Hard: 50 numbers removed
    
    for _ in range(num_to_remove):
        row = random.randint(0, 8)
        col = random.randint(0, 8)
        if board[row][col] != 0:
            board[row][col] = 0

# Generate a solved Sudoku puzzle
solved_sudoku = generate_solved_sudoku()

# Print the solved Sudoku puzzle
print("Solved Sudoku Puzzle:")
print_sudoku(solved_sudoku)

# Create a copy of the solved puzzle
unsolved_sudoku = [row[:] for row in solved_sudoku]

# Remove numbers to create a puzzle
difficulty_level = 'medium'  # Change difficulty level as needed ('easy', 'medium', 'hard')
remove_numbers(unsolved_sudoku, difficulty_level)

# Print the unsolved Sudoku puzzle (the generated puzzle)
print("\nUnsolved Sudoku Puzzle:")
print_sudoku(unsolved_sudoku)
반응형

'프로그래밍 > Python' 카테고리의 다른 글

[python] 알고리즘 - 탐색  (0) 2023.09.27
[python] 알고리즘 - 정렬  (0) 2023.09.27
[python] sudoku 만들기  (0) 2023.09.27
[python] How to send text messages with Python for Free  (0) 2023.09.26
[python] algorithm, 알고리즘  (0) 2023.09.20

+ Recent posts