반응형

파이썬 식별자(Identifiers)

파이썬 식별자는 변수, 함수, 클래스, 모듈 또는 다른 객체를 식별하는데 사용되는 이름을 뜻합니다. 
식별자는 문자 A부터 Z 또는 a에서 z 또는 밑줄 (_)로 시작하며 한 개 또는 그 이상의 문자로 구성됩니다. 
파이썬에서는 @, $, %와 같은 특수 문자를 식별자 내에서 사용할 수 없습니다. 
파이썬은 대소 문자를 구별하는 프로그래밍 언어이기 때문에 Manpower와 manpower는 Python에서 두 개의 다른 식별자로 처리됩니다. 

다음은 Python 식별자의 명명 규칙입니다.
 - 클래스 이름은 대문자로 시작합니다. 다른 모든 식별자는 소문자로 시작합니다.
 - 1개의 밑줄로 시작: 내부적으로 사용되는 변수입니다.
 - 1개의 밑줄로 종료: 파이썬 기본 키워드와 충돌을 피하려고 사용됩니다.
 - 2개의 밑줄로 시작: 클래스 속성으로 사용합니다.
 - 2개의 밑줄로 종료: 사용자가 조정할 수 있는 네임스페이스 안의 속성입니다.
 - 식별자는 숫자로 시작될 수 없다. 1variable은 오류이지만 variable1 은 괜찮다.
 - 키워드는 식별자로 사용할 수 없다.
 - !, @, #, $, % 등 특수 기호는 우리 식별자에서 사용할 수 없다.
 - 식별자의 길이는 제한이 없다.

python3에서는 유니코드 문자를 식별자로 사용할 수 있습니다. 즉, 한글로도 변수명을 지을 수 있지만 권장되지는 않는다고 합니다.

반응형
반응형

[python] calendar 모듈, 달력 사용하기  https://docs.python.org/ko/3/library/calendar.html

 

calendar — General calendar-related functions

Source code: Lib/calendar.py This module allows you to output calendars like the Unix cal program, and provides additional useful functions related to the calendar. By default, these calendars have...

docs.python.org

# https://docs.python.org/ko/3/library/calendar.html
import calendar

yy = 2023
mm = 5

#display the calendar
print(calendar.month(yy,mm))

#calendar 모듈 내용 확인
print(dir(calendar))

calendar 모듈을 좀 더 살펴보겠습니다.

문제 1. calendar 모듈을 임포트하는 문장을 완성하세요.

>>> ____ calendar

calendar 모듈에 무엇이 있는지 살펴보세요.

>>> dir(calendar)
['Calendar', 'EPOCH', 'FRIDAY', 'February', 'HTMLCalendar', 'IllegalMonthError', 'IllegalWeekdayError', 'January', 'LocaleHTMLCalendar', 'LocaleTextCalendar', 'MONDAY', 'SATURDAY', 'SUNDAY', 'THURSDAY', 'TUESDAY', 'TextCalendar', 'WEDNESDAY', '_EPOCH_ORD', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_colwidth', '_locale', '_localized_day', '_localized_month', '_monthlen', '_nextmonth', '_prevmonth', '_spacing', 'c', 'calendar', 'datetime', 'day_abbr', 'day_name', 'different_locale', 'error', 'firstweekday', 'format', 'formatstring', 'isleap', 'leapdays', 'main', 'mdays', 'month', 'month_abbr', 'month_name', 'monthcalendar', 'monthrange', 'prcal', 'prmonth', 'prweek', 'repeat', 'setfirstweekday', 'sys', 'timegm', 'week', 'weekday', 'weekheader']

이와 같이 모듈은 수많은 공구가 들어 있는 '공구통'이라고 생각할 수 있습니다.

문제 2. calendar 모듈에 leap이라는 문자열을 포함하는 이름은 어떤 것이 있는지 찾아보세요.1

>>> [x for x in dir(calendar) if 'leap' in x]
[____, ____]

문제 3. 주어진 해가 윤년인지 아닌지 판별하는 함수의 사용법을 확인해보세요.

>>> help(____)
Help on function ____ in module calendar:

____(year)
    Return True for leap years, False for non-leap years.

문제 4. 이 함수를 사용해서 2077년이 윤년인지 아닌지 확인해보세요.

>>> ____
False

https://github.com/ychoi-kr/wikidocs-chobo-python/blob/master/ch05/using_modules.ipynb

 

GitHub - ychoi-kr/wikidocs-chobo-python: 《왕초보를 위한 파이썬》 예제 코드

《왕초보를 위한 파이썬》 예제 코드. Contribute to ychoi-kr/wikidocs-chobo-python development by creating an account on GitHub.

github.com

{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "attractive-marketing",
   "metadata": {},
   "outputs": [],
   "source": [
    "#문제 1\n",
    "import calendar"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "greatest-event",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Calendar',\n",
       " 'EPOCH',\n",
       " 'FRIDAY',\n",
       " 'February',\n",
       " 'HTMLCalendar',\n",
       " 'IllegalMonthError',\n",
       " 'IllegalWeekdayError',\n",
       " 'January',\n",
       " 'LocaleHTMLCalendar',\n",
       " 'LocaleTextCalendar',\n",
       " 'MONDAY',\n",
       " 'SATURDAY',\n",
       " 'SUNDAY',\n",
       " 'THURSDAY',\n",
       " 'TUESDAY',\n",
       " 'TextCalendar',\n",
       " 'WEDNESDAY',\n",
       " '_EPOCH_ORD',\n",
       " '__all__',\n",
       " '__builtins__',\n",
       " '__cached__',\n",
       " '__doc__',\n",
       " '__file__',\n",
       " '__loader__',\n",
       " '__name__',\n",
       " '__package__',\n",
       " '__spec__',\n",
       " '_colwidth',\n",
       " '_locale',\n",
       " '_localized_day',\n",
       " '_localized_month',\n",
       " '_monthlen',\n",
       " '_nextmonth',\n",
       " '_prevmonth',\n",
       " '_spacing',\n",
       " 'c',\n",
       " 'calendar',\n",
       " 'datetime',\n",
       " 'day_abbr',\n",
       " 'day_name',\n",
       " 'different_locale',\n",
       " 'error',\n",
       " 'firstweekday',\n",
       " 'format',\n",
       " 'formatstring',\n",
       " 'isleap',\n",
       " 'leapdays',\n",
       " 'main',\n",
       " 'mdays',\n",
       " 'month',\n",
       " 'month_abbr',\n",
       " 'month_name',\n",
       " 'monthcalendar',\n",
       " 'monthrange',\n",
       " 'prcal',\n",
       " 'prmonth',\n",
       " 'prweek',\n",
       " 'repeat',\n",
       " 'setfirstweekday',\n",
       " 'sys',\n",
       " 'timegm',\n",
       " 'week',\n",
       " 'weekday',\n",
       " 'weekheader']"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dir(calendar)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "silver-delhi",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['isleap', 'leapdays']"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#문제 2\n",
    "[x for x in dir(calendar) if 'leap' in x]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "ultimate-collaboration",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function isleap in module calendar:\n",
      "\n",
      "isleap(year)\n",
      "    Return True for leap years, False for non-leap years.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "#문제 3\n",
    "help(calendar.isleap)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "ancient-newport",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#문제 4\n",
    "calendar.isleap(2077)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "arbitrary-eleven",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
반응형
반응형

[python] 소스경로와 실행경로가 다를때 os.chdir()

# 파이썬 컴파일 경로가 달라서 현재 폴더의 이미지를 호출하지 못할때 작업디렉토리를 변경한다.
import os
from pathlib import Path
# src 상위 폴더를 실행폴더로 지정하려고 한다.
real_path = Path(__file__).parent.parent
print(real_path)
#작업 디렉토리 변경
os.chdir(real_path)
# 파이썬 컴파일 경로가 달라서 현재 폴더의 이미지를 호출하지 못할때 작업디렉토리를 변경한다. 
import os
from pathlib import Path
# src 상위 폴더를 실행폴더로 지정하려고 한다.
real_path = Path(__file__).parent.parent
print(real_path)
#작업 디렉토리 변경
os.chdir(real_path)
처리내용 os 및 os.path pathlib
현재의 디렉토리를 취득 os.getcwd() Path.cwd()
맨 앞의 ~를 홈 디렉토리에 치환 os.path.expanduser() Path.expanduser(), Path.home()
경로의 존재 확인 os.path.exists() Path.exists()
디렉토리인가를 판단 os.path.isdir() Path.is_dir()
파일인가를 판단 os.path.isfile() Path.is_file()
심볼릭 링크인가를 판단 os.path.islink() Path.is_symlink()
절대경로인가를 판단 os.path.isabs() PurePath.is_absolute()
절대경로로 변환 os.path.abspath() Path.resolve()
status를 취득 os.stat() Path.stat(), Path.owner(), Path.group()
경로를 연결 os.path.join() PurePath.joinpath()
파일명을 취득 os.path.basename() PurePath.name
새로운 디렉토리를 취득 os.path.dirname() PurePath.parent
확장자를 분할·취득 os.path.splitext() PurePath.suffix

Pathlib - 객체 지향 파일 시스템 경로

객체 지향 파일 시스템 경로, 즉 파일을 객체로 관리하겠다는것 같음.
아래 그림은 Pathlib 내부 객체들의 상속관계로, 가장 기본적인 객체는 PurePath임을 알 수있음.
대략적인 객체간 의미와 관계를 알기 위해 라이브러리를 뜯어봄 -> pathlib.py

차이점

os.path  Pathlib의 가장 큰 차이점은, 경로를 문자열로 다루냐, 객체로 다루냐 차이인데, 모든 것이 객체로 이루어진 python 인 만큼, Pathlib가 자연스러운 모듈이며 객체 내부적으로 정의된 연산자를 사용할 수 있어 경로에 있어 더 자연스러운 표현이 가능함.

기본적인 사용법은 알아야, 나중에 쓸 일이 있으면 찾아보지 않고 쓸 수 있으니 대충정리해보자.

1. 탐색

논리적 경로와, 절대 경로와의 구분을 잘 해야 함. 논리 경로 상에서, 앵커나 빈 경로는 넘어갈 수 없음. 코드상으로 경로 탐색에 사용할 수 있는 것은, .parent, .parents, .iterdir() 등이 있음.

상위 디렉토리로 넘어가기 위해선, .parent를 사용하나, 사용하기 전 절대경로로 바꾸고, 현재 경로가 디렉토리이면, .iterdir()를 통해 자식 경로를 얻을 수 있음.

from pathlib import Path

p = Path('.') # PosixPath('.')
p.resolve() # os.path.abspath()

p.resolve().parent
list(p.iterdir()) # iteration, list 변환, = os.listdir()

2. 연산자

연산자를 사용하여 경로 조합 가능.

from pathlib import Path

p = Path.home() # os.path.expanduser()
p_sub = p / 'foo' / 'bar' # PosixPath('/Users/kyuu/foo/bar')
p_sub = Path(p, 'foo', 'bar') # os.path.join() 모방

https://docs.python.org/ko/3/library/pathlib.html

반응형
반응형

Program made with Python and Pygame module for visualizing sorting algorithms

Support this project by leaving a ⭐

 

  • Run: python3 src/main.py

https://github.com/LucasPilla/Sorting-Algorithms-Visualizer/tree/master

 

GitHub - LucasPilla/Sorting-Algorithms-Visualizer: Program made with Python and Pygame module for visualizing sorting algorithms

Program made with Python and Pygame module for visualizing sorting algorithms - GitHub - LucasPilla/Sorting-Algorithms-Visualizer: Program made with Python and Pygame module for visualizing sorting...

github.com

반응형
반응형

[python] Use Phone Camera with python 

 

https://thecleverprogrammer.com/2021/01/05/use-phone-camera-with-python/

 

Use Phone Camera with Python | Aman Kharwal

In this article, I will walk you through how to use your phone camera with Python for computer vision. Use the Phone Camera with Python.

thecleverprogrammer.com

install CV : https://pypi.org/project/opencv-python/  

""" https://thecleverprogrammer.com/2021/01/05/use-phone-camera-with-python/

    https://pypi.org/project/opencv-python/
    > pip install opencv-python
    > pip install opencv-contrib-python
"""
import cv2
import numpy as np

url = "Your IP Address/video"

cap = cv2.VideoCapture(url)

while(True):
    camera, frame = cap.read()
    if frame is not None:
        cv2.imshow("Frame", frame)
    q = cv2.waitKey(1)
    if q==ord("q"):
        break

cv2.destroyAllWindows()

 

https://stackoverflow.com/questions/50185654/opencv-load-video-from-url

 

OpenCV load video from url

I have a video file (i.e. https://www.example.com/myvideo.mp4) and need to load it with OpenCV. Doing the equivalent with an image is fairly trivial: imgReq = requests.get("https://www.example.com/

stackoverflow.com

 

 

 

반응형
반응형

Google 지도 서비스용 Python 클라이언트

파이썬을 사용합니까? 무언가를 지오코딩하고 싶습니까? 방향을 찾고 계십니까? 아마도 방향의 행렬일까요? 이 라이브러리는 Google Maps Platform 웹 서비스를 Python 애플리케이션에 제공합니다.

Google Maps Services용 Python 클라이언트는 다음 Google Maps API용 Python 클라이언트 라이브러리입니다.

  • 길찾기 API
  • 거리 행렬 API
  • 고도 API
  • 지오코딩 API
  • 지리적 위치 API
  • 시간대 API
  • 도로 API
  • 장소 API
  • 지도 정적 API
  • 주소 확인 API

 

요구 사항

  • 파이썬 3.5 이상.
  • Google 지도 API 키입니다.

API 키

각 Google 지도 웹 서비스 요청에는 API 키 또는 클라이언트 ID가 필요합니다. API 키는 Google Cloud Console 'API 및 서비스' 탭의 '사용자 인증 정보' 페이지에서 생성됩니다 .

Google Maps Platform 시작하기 및 API 키 생성/제한에 대한 자세한 내용은 Google 문서에서 Google Maps Platform 시작하기를 참조하세요.

중요: 이 키는 서버에서 비밀로 유지되어야 합니다.

설치

$ pip install -U googlemaps

연결/읽기 제한 시간을 지정하려면 요청 2.4.0 이상이 필요합니다.

 

 

https://pypi.org/project/googlemaps/

 

googlemaps

Python client library for Google Maps Platform

pypi.org

 

https://github.com/googlemaps/google-maps-services-python

 

GitHub - googlemaps/google-maps-services-python: Python client library for Google Maps API Web Services

Python client library for Google Maps API Web Services - GitHub - googlemaps/google-maps-services-python: Python client library for Google Maps API Web Services

github.com

 

반응형
반응형

파이썬 컴파일 위치에 따라 import에 이슈가 발생하곤 한다. 

파일 실행시 이미지가 상대경로라면

프로그램 파일 상단에 작업디렉토리 변경을 통해서 현재 파일의 이슈를 줄일 수 있다. 

 

1.현재 파일의 이름 & 경로

import os

#현재 파일 이름
print(__file__)

#현재 파일 실제 경로
print(os.path.realpath(__file__))

#현재 파일 절대 경로
print(os.path.abspath(__file__))

2.현재 파일의 디렉토리 경로

import os

#현재 폴더 경로; 작업 폴더 기준
print(os.getcwd())

#현재 파일의 폴더 경로; 작업 파일 기준
print(os.path.dirname(os.path.realpath(__file__)))

3.현재 디렉토리의 파일 리스트

import os
print(os.listdir(os.getcwd()))

4.작업 디렉토리 변경

import os
os.chdir("/home/dada/test/")
반응형
반응형

python에서 pygame 실행해보기 aliens  https://www.pygame.org/wiki/GettingStarted

 

anaconda 설치하고 가상환경 들어가서 파이썬 버전(3.10 이상) 확인하고 

pygame 인스톨 후 실행. 

-- pygame 외계인 게임실행하기 

anaconda shell에서 

> pip install -U pygame

> python -m pygame.examples.aliens

https://www.pygame.org/wiki/GettingStarted

(p_pygame) PS D:\_py_project\> conda deactivate
(base) PS D:\_py_project\> conda activate p_pygame
(p_pygame) PS D:\_py_project\> pip install -U pygame
Requirement already satisfied: pygame in c:\programdata\anaconda3\envs\p_pygame\lib\site-packages (2.4.0)
(p_pygame) PS D:\_py_project\> python -m pygame.examples.aliens

반응형

+ Recent posts