반응형
반응형

[python] Working With Mathematical Operations and Permutations. 수학적 연산과 순열

 

https://blog.stackademic.com/ultimate-python-cheat-sheet-practical-python-for-everyday-tasks-c267c1394ee8

 

Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks

(My Other Ultimate Guides)

blog.stackademic.com

 


1. Basic Arithmetic Operations
    To perform basic arithmetic:

sum = 7 + 3  # Addition
difference = 7 - 3  # Subtraction
product = 7 * 3  # Multiplication
quotient = 7 / 3  # Division
remainder = 7 % 3  # Modulus (Remainder)
power = 7 ** 3  # Exponentiation

 

2. Working with Complex Numbers
    To work with complex numbers:

z = complex(2, 3)  # Create a complex number 2 + 3j
real_part = z.real  # Retrieve the real part
imaginary_part = z.imag  # Retrieve the imaginary part
conjugate = z.conjugate()  # Get the conjugate




3. Mathematical Functions
    Common math functions:

import math
root = math.sqrt(16)  # Square root
logarithm = math.log(100, 10)  # Logarithm base 10 of 100
sine = math.sin(math.pi / 2)  # Sine of 90 degrees (in radians)




4. Generating Permutations
    Easy way to generate permutations from a given set:

from itertools import permutations
paths = permutations([1, 2, 3])  # Generate all permutations of the list [1, 2, 3]
for path in paths:
    print(path)


5. Generating Combinations
    Easy way to generate combinations:

from itertools import combinations
combos = combinations([1, 2, 3, 4], 2)  # Generate all 2-element combinations
for combo in combos:
    print(combo)


6. Random Number Generation
    To get a random number:

import random
num = random.randint(1, 100)  # Generate a random integer between 1 and 100


7. Working with Fractions
    When you need to work with fractions:

from fractions import Fraction
f = Fraction(3, 4)  # Create a fraction 3/4
print(f + 1)  # Add a fraction and an integer


8. Statistical Functions
   To get Average, Median, and Standard Deviation:

import statistics
data = [1, 2, 3, 4, 5]
mean = statistics.mean(data)  # Average
median = statistics.median(data)  # Median
stdev = statistics.stdev(data)  # Standard Deviation


9. Trigonometric Functions
    To work with trigonometry:

import math
angle_rad = math.radians(60)  # Convert 60 degrees to radians
cosine = math.cos(angle_rad)  # Cosine of the angle


10. Handling Infinity and NaN
    To work with Infinity and NaN:

import math
infinity = math.inf  # Representing infinity
not_a_number = math.nan  # Representing a non-number (NaN)



 

 
반응형
반응형

[python] 폴더 안의 파일들 이름의 공백 또는 - 를 언더바로 변경하는 프로그램

 

공백( ) 또는 하이픈(-)을 언더바(_)로 변경하는 프로그램을 작성할 수 있습니다. 이 프로그램은 지정된 폴더 내 모든 파일의 이름을 확인하고, 공백 또는 하이픈이 포함된 경우 이를 언더바로 대체하여 이름을 변경합니다.

 

# 파이썬 컴파일 경로가 달라서 현재 폴더의 이미지를 호출하지 못할때 작업디렉토리를 변경한다. 
import os
from pathlib import Path
# src 상위 폴더를 실행폴더로 지정하려고 한다.
###real_path = Path(__file__).parent.parent
real_path = Path(__file__).parent
print(real_path)
#작업 디렉토리 변경
os.chdir(real_path) 


def replace_spaces_in_filenames(folder_path):
    # 폴더 내 모든 파일을 반복
    for filename in os.listdir(folder_path):
        # 파일의 전체 경로 생성
        old_file_path = os.path.join(folder_path, filename)

        # 파일 이름에 공백이 있는지, -도 _로 변경 확인
        if ' ' in filename or  '-' in filename:
            # 공백을 언더바로 대체
            new_filename = filename.replace(' ', '_').replace('-', '_')
            new_file_path = os.path.join(folder_path, new_filename)

            
            # 파일이 존재할경우 덮어쓸지, 빠져나갈지 
            if os.path.exists(new_file_path):
                overwrite = input(f"'{new_file_path}' already exists. Overwrite? (y/n): ")
                if overwrite.lower() == 'y':
                    os.remove(new_file_path)
                else:
                    print("Operation canceled.")
                    exit()
            # 파일 이름 변경
            os.rename(old_file_path, new_file_path)
            
            
            print(f"Renamed: '{filename}' -> '{new_filename}'")
        else:
            print(f"No change: '{filename}'")

# 사용 예시
folder_path = 'path_to_your_folder'  # 여기에 폴더 경로를 입력하세요 
replace_spaces_in_filenames(folder_path)

프로그램 설명

  1. os 모듈: 파일 경로와 관련된 작업을 수행하기 위해 os 모듈을 사용합니다.
  2. 폴더 내 파일 탐색:
    • os.listdir(folder_path)를 사용하여 지정된 폴더 내의 모든 파일 및 하위 디렉토리 이름을 가져옵니다.
    • for filename in os.listdir(folder_path)를 사용하여 각 파일을 순회합니다.
  3. 공백과 하이픈을 언더바로 변경:
    • if ' ' in filename or '-' in filename: 조건문을 사용하여 파일 이름에 공백 또는 하이픈이 포함되어 있는지 확인합니다.
    • filename.replace(' ', '_').replace('-', '_')를 사용하여 공백과 하이픈을 언더바로 대체합니다.
  4. 파일 이름 변경:
    • os.rename(old_file_path, new_file_path)를 사용하여 파일 이름을 변경합니다.
  5. 사용 방법:
    • folder_path에 파일 이름을 변경할 폴더의 경로를 입력합니다.
    • 프로그램을 실행하면 폴더 내 모든 파일의 이름에서 공백과 하이픈이 언더바로 변경됩니다.

사용 예시

폴더 경로를 지정하여 프로그램을 실행하면, 그 폴더 안의 모든 파일 이름에서 공백 또는 하이픈이 언더바로 변경됩니다. 예를 들어, path_to_your_folder가 C:/Users/YourName/Documents/TestFolder인 경우:

반응형
반응형

1. Navigating File Paths

To craft and dissect paths, ensuring compatibility across realms (operating systems):

import os
# Craft a path compatible with the underlying OS
path = os.path.join('mystic', 'forest', 'artifact.txt')
# Retrieve the tome's directory
directory = os.path.dirname(path)
# Unveil the artifact's name
artifact_name = os.path.basename(path)

2. Listing Directory Contents

To reveal all entities within a mystical directory:

import os
contents = os.listdir('enchanted_grove')
print(contents)

3. Creating Directories

To conjure new directories within the fabric of the filesystem:

import os
# create a single directory
os.mkdir('alchemy_lab')
# create a hierarchy of directories
os.makedirs('alchemy_lab/potions/elixirs')

4. Removing Files and Directories

To erase files or directories, banishing their essence:

import os
# remove a file
os.remove('unnecessary_scroll.txt')
# remove an empty directory
os.rmdir('abandoned_hut')
# remove a directory and its contents
import shutil
shutil.rmtree('cursed_cavern')

5. Executing Shell Commands

To invoke the shell’s ancient powers directly from Python:

import subprocess
# Invoke the 'echo' incantation
result = subprocess.run(['echo', 'Revealing the arcane'], capture_output=True, text=True)
print(result.stdout)

6. Working with Environment Variables

To read and inscribe upon the ethereal environment variables:

import os
# Read the 'PATH' variable
path = os.environ.get('PATH')
# Create a new environment variable
os.environ['MAGIC'] = 'Arcane'

7. Changing the Current Working Directory

To shift your presence to another directory within the filesystem:

import os
# Traverse to the 'arcane_library' directory
os.chdir('arcane_library')

8. Path Existence and Type

To discern the existence of paths and their nature — be they file or directory:

import os
# Check if a path exists
exists = os.path.exists('mysterious_ruins')
# Ascertain if the path is a directory
is_directory = os.path.isdir('mysterious_ruins')
# Determine if the path is a file
is_file = os.path.isfile('ancient_manuscript.txt')

9. Working with Temporary Files

To summon temporary files and directories, fleeting and ephemeral:

import tempfile
# Create a temporary file
temp_file = tempfile.NamedTemporaryFile(delete=False)
print(temp_file.name)
# Erect a temporary directory
temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)

10. Getting System Information

To unveil information about the host system, its name, and the enchantments it supports:

import os
import platform
# Discover the operating system
os_name = os.name  # 'posix', 'nt', 'java'
# Unearth detailed system information
system_info = platform.system()  # 'Linux', 'Windows', 'Darwin'

 

 
반응형
반응형

[python] Working With Dictionaries

1. Creating a Dictionary

To forge a new dictionary:

# A tome of elements and their symbols
elements = {'Hydrogen': 'H', 'Helium': 'He', 'Lithium': 'Li'}

2. Adding or Updating Entries

To add a new entry or update an existing one:

elements['Carbon'] = 'C'  # Adds 'Carbon' or updates its value to 'C'

3. Removing an Entry

To banish an entry from the dictionary:

del elements['Lithium']  # Removes the key 'Lithium' and its value

4. Checking for Key Existence

To check if a key resides within the dictionary:

if 'Helium' in elements:
    print('Helium is present')

5. Iterating Over Keys

To iterate over the keys in the dictionary:

for element in elements:
    print(element)  # Prints each key

6. Iterating Over Values

To traverse through the values in the dictionary:

for symbol in elements.values():
    print(symbol)  # Prints each value

7. Iterating Over Items

To journey through both keys and values together:

for element, symbol in elements.items():
    print(f'{element}: {symbol}')

8. Dictionary Comprehension

To conjure a new dictionary through an incantation over an iterable:

# Squares of numbers from 0 to 4
squares = {x: x**2 for x in range(5)}

9. Merging Dictionaries

To merge two or more dictionaries, forming a new alliance of their entries:

alchemists = {'Paracelsus': 'Mercury'}
philosophers = {'Plato': 'Aether'}
merged = {**alchemists, **philosophers}  # Python 3.5+

10. Getting a Value with Default

To retrieve a value safely, providing a default for absent keys:

element = elements.get('Neon', 'Unknown')  # Returns 'Unknown' if 'Neon' is not found

 

https://blog.stackademic.com/ultimate-python-cheat-sheet-practical-python-for-everyday-tasks-c267c1394ee8

 

Ultimate Python Cheat Sheet: Practical Python For Everyday Tasks

(My Other Ultimate Guides)

blog.stackademic.com

 

반응형
반응형

[python] 폴더 안의 .webp 이미지를 .png 로 변환

 

.webp 이미지를 .png로 변환하는 Python 프로그램을 작성할 수 있습니다. 이를 위해 Pillow 라이브러리를 사용합니다. Pillow는 Python의 이미지 처리 라이브러리로, 다양한 이미지 형식을 다룰 수 있습니다.

다음은 특정 폴더 내의 모든 .webp 이미지를 .png로 변환하는 프로그램입니다:

1. Pillow 설치

먼저 Pillow 라이브러리를 설치해야 합니다. 터미널이나 명령 프롬프트에서 다음 명령어를 실행하세요:

pip install Pillow

2. .webp 이미지를 .png로 변환하는 코드

아래 코드 예시는 지정된 폴더 내의 모든 .webp 파일을 .png 파일로 변환합니다:

from PIL import Image
import os

def convert_webp_to_png(folder_path):
    # 폴더 내 모든 파일을 반복
    for filename in os.listdir(folder_path):
        if filename.endswith(".webp"):
            # 파일의 전체 경로 생성
            webp_file_path = os.path.join(folder_path, filename)

            # .webp 파일을 열고 .png로 저장
            png_filename = filename[:-5] + ".png"  # 파일 확장자를 .png로 변경
            png_file_path = os.path.join(folder_path, png_filename)

            with Image.open(webp_file_path) as img:
                img.save(png_file_path, "png")
            
            print(f"Converted: '{filename}' -> '{png_filename}'")

# 사용 예시
folder_path = 'path_to_your_folder'  # 여기에 폴더 경로를 입력하세요
convert_webp_to_png(folder_path)

코드 설명

  1. Pillow 라이브러리 사용: Pillow의 Image 모듈을 사용하여 이미지를 열고 변환합니다.
  2. 폴더 내 파일 탐색:
    • os.listdir(folder_path)를 사용하여 지정된 폴더 내의 모든 파일을 가져옵니다.
    • if filename.endswith(".webp"): 조건문을 사용하여 .webp 확장자를 가진 파일만 필터링합니다.
  3. 파일 경로 생성:
    • webp_file_path는 원본 .webp 파일의 전체 경로입니다.
    • png_filename은 .webp 확장자를 .png로 대체한 새 파일 이름입니다.
    • png_file_path는 변환된 .png 파일의 전체 경로입니다.
  4. 이미지 변환 및 저장:
    • Image.open(webp_file_path)를 사용하여 .webp 파일을 열고, img.save(png_file_path, "png")를 사용하여 .png 파일로 저장합니다.
  5. 사용 방법:
    • folder_path 변수에 변환할 .webp 파일이 있는 폴더 경로를 입력합니다.
    • 프로그램을 실행하면 폴더 내 모든 .webp 파일이 .png 파일로 변환됩니다.

사용 예시

예를 들어, 폴더 경로가 C:/Users/YourName/Documents/Images인 경우:

folder_path = 'C:/Users/YourName/Documents/Images'
convert_webp_to_png(folder_path)

위 코드를 실행하면 해당 폴더 내의 모든 .webp 파일이 .png 형식으로 변환됩니다.

반응형
반응형

[python] 폴더 안의 파일들 이름의 공백 또는 - 를 언더바로 변경하는 프로그램

 

공백( ) 또는 하이픈(-)을 언더바(_)로 변경하는 프로그램을 작성할 수 있습니다. 이 프로그램은 지정된 폴더 내 모든 파일의 이름을 확인하고, 공백 또는 하이픈이 포함된 경우 이를 언더바로 대체하여 이름을 변경합니다.

 

import os

def replace_spaces_and_hyphens_in_filenames(folder_path):
    # 폴더 내 모든 파일을 반복
    for filename in os.listdir(folder_path):
        # 파일의 전체 경로 생성
        old_file_path = os.path.join(folder_path, filename)

        # 파일 이름에 공백 또는 하이픈이 있는지 확인
        if ' ' in filename or '-' in filename:
            # 공백과 하이픈을 언더바로 대체
            new_filename = filename.replace(' ', '_').replace('-', '_')
            new_file_path = os.path.join(folder_path, new_filename)

            # 파일 이름 변경
            os.rename(old_file_path, new_file_path)
            print(f"Renamed: '{filename}' -> '{new_filename}'")
        else:
            print(f"No change: '{filename}'")

# 사용 예시
folder_path = 'path_to_your_folder'  # 여기에 폴더 경로를 입력하세요
replace_spaces_and_hyphens_in_filenames(folder_path)

프로그램 설명

  1. os 모듈: 파일 경로와 관련된 작업을 수행하기 위해 os 모듈을 사용합니다.
  2. 폴더 내 파일 탐색:
    • os.listdir(folder_path)를 사용하여 지정된 폴더 내의 모든 파일 및 하위 디렉토리 이름을 가져옵니다.
    • for filename in os.listdir(folder_path)를 사용하여 각 파일을 순회합니다.
  3. 공백과 하이픈을 언더바로 변경:
    • if ' ' in filename or '-' in filename: 조건문을 사용하여 파일 이름에 공백 또는 하이픈이 포함되어 있는지 확인합니다.
    • filename.replace(' ', '_').replace('-', '_')를 사용하여 공백과 하이픈을 언더바로 대체합니다.
  4. 파일 이름 변경:
    • os.rename(old_file_path, new_file_path)를 사용하여 파일 이름을 변경합니다.
  5. 사용 방법:
    • folder_path에 파일 이름을 변경할 폴더의 경로를 입력합니다.
    • 프로그램을 실행하면 폴더 내 모든 파일의 이름에서 공백과 하이픈이 언더바로 변경됩니다.

사용 예시

폴더 경로를 지정하여 프로그램을 실행하면, 그 폴더 안의 모든 파일 이름에서 공백 또는 하이픈이 언더바로 변경됩니다. 예를 들어, path_to_your_folder가 C:/Users/YourName/Documents/TestFolder인 경우:

folder_path = 'C:/Users/YourName/Documents/TestFolder'
replace_spaces_and_hyphens_in_filenames(folder_path)

 

 

반응형

+ Recent posts