반응형
반응형

[python] 난수 10자리에서 영문 숫자 분포가 골고루 들어갈수있게

 

import random
import string

def generate_balanced_random_string(length=10):
    # 원하는 비율로 대문자, 소문자, 숫자 개수 설정
    num_uppercase = 4  # 대문자 4개
    num_lowercase = 3  # 소문자 3개
    num_digits = 3     # 숫자 3개

    # 각 문자 유형에서 원하는 만큼 선택
    uppercase_letters = random.choices(string.ascii_uppercase, k=num_uppercase)
    lowercase_letters = random.choices(string.ascii_lowercase, k=num_lowercase)
    digits = random.choices(string.digits, k=num_digits)

    # 모든 문자들을 합쳐서 무작위로 섞음
    random_string = uppercase_letters + lowercase_letters + digits
    random.shuffle(random_string)

    # 리스트를 문자열로 변환하여 반환
    return ''.join(random_string)

# 함수 호출
random_string = generate_balanced_random_string()
print(f"균형 잡힌 10자리 난수: {random_string}")
반응형
반응형

[python] 랜덤 난수 생성해서 엑셀에 저장하기 

"""   
랜덤으로 생성된 문자열을 엑셀 파일에 저장
"""
import random
import string
import os
from captcha.image import ImageCaptcha
import pandas as pd  # pandas 라이브러리를 사용하여 엑셀 파일 저장

# 2023-05-26 ngio add
# 파이썬 컴파일 경로가 달라서 현재 폴더의 이미지를 호출하지 못할때 작업디렉토리를 변경한다. 
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) 


# 랜덤 6자리 문자열 생성 함수
def generate_random_string(length=6):
    # string.ascii_uppercase: 영문 대문자 A-Z만을 포함합니다.
    # string.ascii_lowercase: 영문 소문자 a-z만을 포함합니다.
    # characters = string.ascii_letters + string.digits  # 영문 대소문자 + 숫자
    characters = string.ascii_uppercase + string.digits
    return ''.join(random.choices(characters, k=length)) 

# 초기 데이터
data = [['QWE123', 10001], ['RTY456', 10002]]

# 반복문을 통해 데이터 추가
for i in range(1, 10):
    #letter = chr(64 + i)  # A: 65 -> B: 66 -> C: 67 -> ...
    letter = generate_random_string();
    data.append([letter, (10002 + i)])

print(data)
print("\n\n")

# 중복 값 확인 함수
def check_duplicates(data):
    # 리스트를 튜플로 변환 (리스트는 set에 직접 넣을 수 없기 때문)
    data_as_tuples = [tuple(item) for item in data]
    
    # 집합의 크기와 리스트의 크기를 비교
    if len(data_as_tuples) != len(set(data_as_tuples)):
        print("중복된 값이 있습니다.")
    else:
        print("중복된 값이 없습니다.")

# 함수 호출
check_duplicates(data)
print("\n\n")


# DataFrame으로 변환
df = pd.DataFrame(data, columns=['random_word', 'word_index'])

# 결과 출력
print(df)
print("\n\n")
반응형
반응형

## pyenv lets you easily switch between multiple versions of Python. It's simple, unobtrusive, and follows the UNIX tradition of single-purpose tools that do one thing well.

This project was forked from rbenv and ruby-build, and modified for Python.

https://github.com/pyenv/pyenv

 

GitHub - pyenv/pyenv: Simple Python version management

Simple Python version management. Contribute to pyenv/pyenv development by creating an account on GitHub.

github.com

## What pyenv does...
* Lets you change the global Python version on a per-user basis.
* Provides support for per-project Python versions.
* Allows you to override the Python version with an environment variable.
* Searches for commands from multiple versions of Python at a time. This may be helpful to test across Python versions with tox.

## In contrast with pythonbrew and pythonz, pyenv does not...
* Depend on Python itself. pyenv was made from pure shell scripts. There is no bootstrap problem of Python.
* Need to be loaded into your shell. Instead, pyenv's shim approach works by adding a directory to your PATH.
* Manage virtualenv. Of course, you can create virtualenv yourself, or pyenv-virtualenv to automate the process.

반응형
반응형

[python]  랜덤 6자리 문자열을 생성하고, 중복되지 않도록 파일명을 지정한 후 이미지 캡차를 저장. captcha

import random
import string
import os
from captcha.image import ImageCaptcha  # ImageCaptcha 라이브러리를 사용해야 합니다.

# 랜덤 6자리 문자열 생성 함수
def generate_random_string(length=6):
    characters = string.ascii_letters + string.digits  # 영문 대소문자 + 숫자
    return ''.join(random.choices(characters, k=length))

# 중복되지 않는 파일명 생성 함수
def get_unique_filename(base_name, extension, directory="./img/"):
    counter = 1
    new_filename = f"{base_name}.{extension}"
    
    # 경로 내 파일명이 중복되면 새로운 파일명 생성
    while os.path.exists(os.path.join(directory, new_filename)):
        new_filename = f"{base_name}_{counter}.{extension}"
        counter += 1
    
    return new_filename

# 메인 로직
def main():
    # 캡차 이미지 생성기 설정
    image = ImageCaptcha(width=280, height=90)

    # 랜덤 6자리 문자열 생성
    captcha_text = generate_random_string()
    print(f"\n랜덤 6자리 문자열: {captcha_text}")

    # 이미지 생성
    data = image.generate(captcha_text)

    # 이미지 저장 경로 지정
    img_directory = "./img/"
    os.makedirs(img_directory, exist_ok=True)  # img 폴더가 없을 경우 생성

    # 중복되지 않는 파일명 생성
    unique_filename = get_unique_filename(captcha_text, 'png', directory=img_directory)

    # 이미지 파일 저장
    image.write(captcha_text, os.path.join(img_directory, unique_filename))

    print(f"이미지가 {unique_filename}으로 저장되었습니다.")

# 프로그램 실행
if __name__ == "__main__":
    main()

 

수정 내용:

  1. generate_random_string() 함수: 랜덤한 6자리 문자열을 생성합니다.
  2. get_unique_filename() 함수: 파일명 중복을 방지하기 위해, 기존에 존재하는 파일이 있을 경우 숫자를 추가하여 고유 파일명을 생성합니다.
  3. 폴더 생성 (os.makedirs()): 이미지 저장 경로(./img/)가 존재하지 않으면 자동으로 폴더를 생성하도록 os.makedirs()를 사용합니다.
  4. os.path.exists(): 파일이 존재하는지 확인하고 중복 파일명을 방지합니다.
  5. 경로 및 파일명 결합 (os.path.join()): OS에 관계없이 적절한 경로를 결합하기 위해 os.path.join()을 사용합니다.

실행 결과:

  • ./img/ 폴더에 랜덤한 문자열을 포함한 이미지가 저장됩니다.
  • 파일명이 중복되면 자동으로 _1, _2 등의 숫자가 추가됩니다.

 

반응형
반응형

[python] Generate Captcha Using Python

 

 

https://www.geeksforgeeks.org/generate-captcha-using-python/

 

Generate Captcha Using Python - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

In this article, we are going to see how to generate a captcha using Python package captcha to generate our own CAPTCHA (Completely Automated Public Turing Test to Tell Computers and Humans Apart) in picture form. CAPTCHA is a form of challenge-response authentication security mechanism. CAPTCHA prevents automated systems from reading the distorted characters in the picture.

Installation:

pip install captcha

Generating image captcha: 

Here we are going to generate an image captcha:

Stepwise implementation:

Step 1: Import module and create an instance of ImageCaptcha().

image = ImageCaptcha(width = 280, height = 90)

Step 2: Create image object with image.generate(CAPTCHA_Text).

data = image.generate(captcha_text)  

Step 3: Save the image to a file image.write().

image.write(captcha_text, 'CAPTCHA.png')

Below is the full implementation:

  • Python3

 

# Import the following modules
from captcha.image import ImageCaptcha
 
# Create an image instance of the given size
image = ImageCaptcha(width = 280, height = 90)
 
# Image captcha text
captcha_text = 'GeeksforGeeks' 
 
# generate the image of the given text
data = image.generate(captcha_text) 
 
# write the image on the given file and save it
image.write(captcha_text, 'CAPTCHA.png')

Output:

Image CAPTCHA

Generating Audio captcha:

Here we are going to generate an audio captcha:

Stepwise implementation:

Step 1: Import module and create an instance of AudioCaptcha().

image = audioCaptcha(width = 280, height = 90)

Step 2: Create an audio object with audio.generate(CAPTCHA_Text).

data = audio.generate(captcha_text)  

Step 3: Save the image to file audio.write().

audio.write(captcha_text, audio_file)

Below is the full implementation:

  • Python3

 

# Import the following modules
from captcha.audio import AudioCaptcha
 
# Create an audio instance
audio = AudioCaptcha() 
 
# Audio captcha text
captcha_text = "5454"
 
# generate the audio of the given text
audio_data = audio.generate(captcha_text)
 
# Give the name of the audio file
audio_file = "audio"+captcha_text+'.wav'
 
# Finally write the audio file and save it
audio.write(captcha_text, audio_file)

Output:

Video Player
 
 
 
00:00
 
00:13
 
 

 

Ready to dive into the future? Mastering Generative AI and ChatGPT is your gateway to the cutting-edge world of AI. Perfect for tech enthusiasts, this course will teach you how to leverage Generative AI and ChatGPT with hands-on, practical lessons. Transform your skills and create innovative AI applications that stand out. Don't miss out on becoming an AI expert – Enroll now and start shaping the future!

반응형
반응형

https://ipython.org/install.html

Installing IPython

There are multiple ways of installing IPython. This page contains simplified installation instructions that should work for most users. Our official documentation contains more detailed instructions for manual installation targeted at advanced users and developers.

If you are looking for installation documentation for the notebook and/or qtconsole, those are now part of Jupyter.

I already have Python

If you already have Python installed and are familiar with installing packages, you can get IPython with pip:

pip install ipython

I am getting started with Python

For new users who want to install a full Python environment for scientific computing and data science, we suggest installing the Anaconda or Canopy Python distributions, which provide Python, IPython and all of its dependences as well as a complete set of open source packages for scientific computing and data science.

  1. Download and install Continuum’s Anaconda or the free edition of Enthought’s Canopy.
  2. Update IPython to the current version using the Terminal:

Anaconda:

conda update conda
conda update ipython

https://pypi.org/project/ipython/

 

ipython

IPython: Productive Interactive Computing

pypi.org

 pip install sympy

https://pypi.org/project/sympy/

 

sympy

Computer algebra system (CAS) in Python

pypi.org

 

반응형

+ Recent posts