반응형

리눅스(우분투)에 설치된 비주얼 스튜디오에서 파이썬을 프로그래밍해보자.


pip가 설치되지 않았다면 설치한다.


폴더를 만들어 준다.


폴더내에 파이썬 소스를 작성할 파일을 만든다. 확장자는 .py로 한다.


Python extension을 설치한다.



Linter pylint가 설치되지 않았다는 메세지가 나온다. Install 한다.


소스를 입력하고 Ctrl+F5키를 누르면 실행된다.

Run - Run Without Debugging을 선택해도 된다.


반응형
Posted by J-sean
반응형

파이썬 모듈인 pySerial을 이용해 간단히 아두이노와 시리얼 통신을 할 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
char state;
 
void setup() {
  // put your setup code here, to run once:
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
  Serial.println("Arduino ready.");
}
 
void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available())
  {
    state = Serial.read();
    while (Serial.available())
    {
      Serial.read();  // 첫 번째 문자만 입력받고 나머지는 버린다.
    }
    
    if (state == '0')
    {
      digitalWrite(LED_BUILTIN, LOW);
      Serial.println("LED OFF");
    } else
    {
      digitalWrite(LED_BUILTIN, HIGH);
      Serial.println("LED ON");
    }
  }
 
  delay(100);
}


위 소스를 컴파일 하고 아두이노에 업로드 한다. 시리얼 모니터를 통해서도 Builtin LED를 제어할 수 있다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import serial
import time
import sys
 
try:
    ser = serial.Serial('COM5'9600, timeout = 1)
    time.sleep(1)
except:
    print("Device can not be found or can not be configured.")
    sys.exit(0)
 
if (ser.readable()):
    print(ser.readline().decode(), end =''# 아두이노 준비 상태 확인.
    # 아두이노에서 Serial.println("Arduino ready"); 명령으로 데이터를 보내기 때문에
    # Serial 통신으로 읽어온 데이터에는 줄바꿈 문자(\r\n)가 이미 포함되어 있다.
    # Serial.print("Arduino ready");으로 바꾸면 end = ''가 필요 없다. 
 
while (True):
    print("\n0: Off, 1: On, q(Q): Quit\nChoose: ", end = '')    
    state = input()
 
    if state == 'q' or state == 'Q':
        break
    elif state == '0':
        ser.write(b'0')
        print(ser.readline().decode(), end = '')
    else:
        ser.write(b'1')
        print(ser.readline().decode(), end = '')
 
    time.sleep(0.1)
 
ser.close()


Windows에서 위 소스를 실행하면 연결된 아두이노의 Builtin LED를 제어할 수 있다.

※ 참고: https://pythonhosted.org/pyserial/




이 프로그램과 Arduino IDE의 시리얼 모니터를 동시에 실행시킬 수는 없다.


반응형
Posted by J-sean
반응형

광학 문자 인식(Optical Character Recognition; OCR)은 사람이 쓰거나 기계로 인쇄한 문자의 영상이나 이미지를 기계가 읽을 수 있는 문자로 변환하는 것이다. 다양한 운영체제를 위한 광학 문자 인식 엔진 Tesseract를 윈도우즈에서 사용해 보자.


Tesseract Windows version을 제공하는 UB Mannheim에 접속해서 적당한 플랫폼의 Tesseract를 다운 받는다.


설치한다.







Additional language data (download)를 클릭한다.


Korean을 선택한다.











Python-tesseract(pytesseract)를 설치한다. Python-tesseract은 Google의 Tesseract-OCR Engine의 wrapper이다.


영문 이미지를 준비한다.



한글 이미지를 준비한다.


1
2
3
4
5
6
7
from PIL import Image
import pytesseract
 
pytesseract.pytesseract.tesseract_cmd = r'D:\Program Files\Tesseract-OCR\tesseract'
 
print(pytesseract.image_to_string(Image.open('English.png')))
#print(pytesseract.image_to_string(Image.open('Korean.png'), lang = 'kor'))


영문, 한글 이미지를 읽고 텍스트를 출력한다.


영문 이미지 결과.


한글 이미지 결과.



Console에서 아래 명령어로도 같은 결과를 얻을 수 있다.

tesseract English.png stdout


tesseract Korean.png stdout -l kor


stdout이 아닌 다른 이름으로 출력을 지정하면 그 이름의 텍스트 파일로 출력된다.

tesseract English.png result


반응형

'AI, ML, DL' 카테고리의 다른 글

[Scraping] 환율 정보를 SMS로 보내기  (3) 2024.01.02
[Scraping] 환율 정보  (0) 2024.01.02
CSV 분석  (0) 2019.01.20
JSON 분석  (0) 2019.01.18
Beautifulsoup XML 분석  (0) 2019.01.15
Posted by J-sean
반응형

유튜브를 시청하다 보면 갑자기 튀어나오는 짜증나는 광고.


아무리 한예슬이 나온다고 해도 어쩔 수 없다. 광고는 짜증난다.


'광고 건너뛰기' 버튼이 나올때 까지 기다렸다 클릭 해야만 다시 시청하던 영상으로 돌아 갈 수 있다. 파이썬 으로 '광고 건너뛰기' 버튼을 자동으로 클릭하는 프로그램을 만들어 보자.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import pyautogui
import datetime
import time
 
size = pyautogui.size()  
print('Screen Size: {0}'.format(size))
 
while True:
    try :
        nowTime = datetime.datetime.now()
        location = pyautogui.locateCenterOnScreen('adskip.png', region = (1200750300100), confidence = 0.7)
        # region = (left, top, width, height)
        # You need to have OpenCV installed for the confidence keyword to work.
 
        if location == None:            
            print("[{0}] Ad not found. (Press 'Ctrl + C' to quit)".format(nowTime.strftime('%H:%M:%S')))
            time.sleep(2.0)
 
            continue
 
        print('[{0}] Ad found at {1}'.format(nowTime.strftime('%H:%M:%S'), location))
        pyautogui.moveTo(location[0], location[1], 1)
        pyautogui.click(button = 'left')
        time.sleep(5.0)
    
    except KeyboardInterrupt :
        print("Thank You.")
        break


Python Source Code



'광고 건너뛰기' 버튼을 찾기 위해 이 그림을 adskip.png로 저장 한다.


실행 로그


영상으로 확인 하자.


반응형
Posted by J-sean
반응형

Python comes preinstalled on most Linux distributions and is available as a package on all others. However, there are certain features you might want to use that are not available on your distro’s package. You can easily compile the latest version of Python from the source.


대부분의 리눅스에는 파이썬이 포함되어 있어 바로 사용할 수 있지만 최신 버전의 파이썬 소스를 직접 컴파일해 사용할 수 도 있다.


파이썬 홈페이지에서 소스 파일 링크 주소를 확인 한다.


wget으로 소스코드를 다운 받는다.


다운 받은 소스 코드 확인.


--enable-optimizations 옵션과 함께 configure를 실행 한다.


make가 없다면 설치 한다.



make로 컴파일 한다. 지정된 디렉토리에 설치 하고 싶다면 make 실행 후 make altinstall 까지 진행 한다.


Warning: make install can overwrite or masquerade the python3 binary. make altinstall is therefore recommended instead of make install since it only installs exec_prefix/bin/pythonversion.


exec_prefix (${exec_prefix}) is installation-dependent and should be interpreted as for GNU software. For example, on most Linux systems, the default is /usr.


./python을 실행하면 컴파일된 파이썬이 실행 된다.


간단히 python명령어로 실행하기 위해 /usr/bin에 소프트 링크를 만들어 준다.


파이썬 홈페이지에서 다운 받았던 압축 파일은 삭제 한다.


dnf로 최신 버전 파이썬을 간단히 설치 할 수 도 있다.



설치가 완료되면 파이썬[버전] 형식으로 실행 할 수 있다.


Python package installer인 pip도 설치 한다. 


pip3 --version 명령으로 pip버전을 확인할 수 있다.


반응형
Posted by J-sean
반응형

Visual Studio 설치 시 'Python 개발' 항목을 선택 하면 Python 언어 지원, Python miniconda등 여러 가지 프로그램이 함께 설치 된다. 다른 응용 프로그램 설치 시 또 다른 버전의 Python이 설치 되기도 하고 업데이트 하기 위해 Python 홈페이지에서 받은 최신 버전 Python을 설치 했다면 최신 버전의 또 다른 Python이 컴퓨터에 설치된다.


Visual Studio에서 컴퓨터에 설치된 여러가지 Python 중 원하는 버전을 선택해 사용할 수 있다.


Python 프로젝트를 만들고 Solution Explorer - Python Environments 마우스 우클릭 - Add Environments... 를 선택 한다.


Existing environment - Environment - 원하는 버전의 Python을 선택 한다. (3.8)


다시 Solution Explorer에서 확인해 보면 원하는 Python이 선택되어 있다. (3.8)



Visual Studio 설치 시 'Python 개발' 항목을 선택하면 'Python 언어 지원'외 특정 버전의 Python이 몇 가지 항목과 함께 설치 된다.


특정 버전의 Python과 기타 항목을 모두 선택 해제 한다.


Python 프로젝트를 만들면 따로 설치한 최신 버전의 Python으로 환경이 구성 된다.


반응형
Posted by J-sean
반응형

SQLite는 별도의 서버 없이 디스크 기반으로 SQL 쿼리를 지원하는 가벼운 C 라이브러리 데이터베이스 이다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import sqlite3
 
dbpath = "fruit.db"
conn = sqlite3.connect(dbpath)
# Opens a connection to the SQLite database file database.
# By default returns a Connection object, unless a custom factory
# is given. You can use ":memory:" to open a database connection to 
# a database that resides in RAM instead of on disk.
cur = conn.cursor()
# The cursor method accepts a single optional parameter factory.
# If supplied, this must be a callable returning an instance of
# Cursor or its subclasses.
 
cur.executescript("""
drop table if exists items;
create table items(
    item_id integer primary key,
    name text unique,
    price integer
);
insert into items(name, price) values("Apple", 800);
insert into items(name, price) values("Orange", 700);
insert into items(name, price) values("Banana", 430);
""")
# This is a nonstandard convenience method for executing
# multiple SQL statements at once. It issues a COMMIT statement
# first, then executes the SQL script it gets as a parameter.
 
conn.commit()
# This method commits the current transaction. If you don’t call
# this method, anything you did since the last call to commit()
# is not visible from other database connections. If you wonder
# why you don’t see the data you’ve written to the database, please
# check you didn’t forget to call this method.
 
cur.execute("select * from items")
# This is a nonstandard shortcut that creates a cursor object by
# calling the cursor() method, calls the cursor’s execute() method
# with the parameters given, and returns the cursor.
item_list = cur.fetchall()
# Fetches all (remaining) rows of a query result, returning a list.
# Note that the cursor’s arraysize attribute can affect the performance
# of this operation. An empty list is returned when no rows are available.
for it in item_list:
    print(it)
 
print()
 
cur.execute("insert into items(name, price) values('Grape', 500)")
conn.commit()
 
cur.execute("select item_id, name, price from items")
item_list = cur.fetchall()
for it in item_list:
    print(it)
 
print()
 
cur.execute("insert into items(name, price) values(?, ?)", ("Strawberry"800))
#conn.commit() 67라인에서 commit()을 호출 하므로 굳이 여기서 할 필요는 없다.
 
data = [("Mango"250), ("Kiwi"740), ("Peach"650)]
cur.executemany("insert into items(name, price) values(?, ?)", data)
# Executes an SQL command against all parameter sequences or mappings found in the
# sequence seq_of_parameters.
conn.commit()
 
cur.execute("select item_id, name, price from items")
item_list = cur.fetchall()
for it in item_list:
    print(it)
 
print()
 
price_range = (600700)
cur.execute("select * from items where name = 'Kiwi' or (price >= ? and price <= ?)",
            price_range)
item_list = cur.fetchall()
for it in item_list:
    print("Name: ", it[1], ", Price: ", it[2])
 
for it in item_list:
    print("ID: %s, Name: %s, Price: %s" %it) # it 자체(튜플)를 전달해도 된다.
 
print("\nStrawberry를 Watermelon으로 변경, Orange 삭제")
 
cur.execute("update items set name = 'Watermelon', price = 1500 where name = 'Strawberry'")
cur.execute("delete from items where name = 'Orange'")
cur.execute("select * from items")
conn.commit()
 
item_list = cur.fetchall()
for it in item_list:
    print(it)
 
cur.close()
conn.close()
cs




fruit.db 파일이 생성 된다.



반응형
Posted by J-sean

CSV 분석

AI, ML, DL 2019. 1. 20. 12:48 |
반응형

Python 기본 라이브러리 csv를 이용해 CSV(comma-separated values) 형식을 분석 할 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import locale
import csv
 
lo = locale.getdefaultlocale()
# Tries to determine the default locale settings and returns them as a tuple of
# the form (language code, encoding).
print("Default language code: " + lo[0], "Default encoding: " + lo[1], sep = "\n", end = "\n\n")
 
filename = "list.csv"
with open(filename, "rt", encoding="euc_kr") as f:
    csv_data = f.read()
 
data = []
rows = csv_data.split("\n")
for row in rows:
    if row == "":
        continue
    cells = row.split(",")
    data.append(cells)
 
for c in data:
    print("%-8s %8s" %(c[1], c[2]))
 
print()
 
#Python csv library
with open(filename, "at", encoding="euc_kr") as f:
    # 'a' - open for writing, appending to the end of the file if it exists
    # For binary read-write access, the mode 'w+b' opens and truncates the file to 0 bytes.
    # 'r+b' opens the file without truncation.
    csv_writer = csv.writer(f, delimiter = ",", quotechar = '"')
    csv_writer.writerow(["101""Math""4300"])
    csv_writer.writerow(["102""Physics""4800"])    
    csv_writer.writerow(["103""English""5700"])
# stream position을 바꾸고 싶으면 io module의 seek()을 f.seek(...)처럼 사용 한다.
# seek(offset[, whence])
# Change the stream position to the given byte offset. offset is interpreted relative to the
# position indicated by whence. The default value for whence is SEEK_SET. Values for whence are:
# SEEK_SET or 0 – start of the stream (the default); offset should be zero or positive
# SEEK_CUR or 1 – current stream position; offset may be negative
# SEEK_END or 2 – end of the stream; offset is usually negative
# Return the new absolute position.
 
with open(filename, "rt", encoding="euc_kr") as f:
    csv_reader = csv.reader(f, delimiter = ",", quotechar = '"')
    for cells in csv_reader:
        if cells == []:
            continue
        print("%-8s %8s" %(cells[1], cells[2]))
cs




list.csv:


결과:


실행 후 list.csv:



반응형
Posted by J-sean