파이썬 정규표현식을 이용한 문자 치환하기

프로그래밍/Python|2021. 7. 5. 16:38
반응형

[코드]

import re

str = "아무개 (010-1111-2222)"

result = re.sub(".*\(|\)", "", str)

print(result)

 

 

[결과]

010-1111-2222

 

 

* 해설

re.sub(첫번째, 두번째, 세번째) 칸의 의미

- 첫번째 : 찾을 문자열 (버티컬바 | 로 구분하면 '또는' 이라는 의미이므로 여러개의 문자열을 찾을 수 있습니다.)

- 두번째 : 변경될 문자열 (예제에서는 빈칸)

- 세번째 : 문자열 변수

 

반응형

댓글()

파이썬 show() 로 출력되는 화면을 이미지 파일(png, pdf)로 저장하기

프로그래밍/Python|2021. 7. 5. 08:58
반응형

from matplotlib import pyplot as plt

plt.savefig('foo.png')

plt.savefig('foo.pdf')

 

[출처] https://stackoverflow.com/questions/9622163/save-plot-to-image-file-instead-of-displaying-it-using-matplotlib

반응형

댓글()

Python 에서 MySQL 연결하기

프로그래밍/Python|2021. 6. 28. 15:24
반응형

필요한 라이브러리를 설치합니다.

# pip3 install mysql-connector

 

예제 (test.py)

import mysql.connector

conn = mysql.connector.connect(
    host = "localhost",
    user = "sysdocu",
    password = "12345678",
    database = "sysdocu"
)
cursor = conn.cursor()

sql = "UPDATE log SET name=%s, status=%s, number=%s"

name = "ROBOT"
status = "have"
number = 35.123874

val = (name, status, number)
cursor.execute(sql, val)
conn.commit()

 

실행

# python3 test.py

반응형

댓글()

[에러] AttributeError: 'DataFrame' object has no attribute 'split'

프로그래밍/Python|2021. 6. 16. 07:35
반응형

데이터 형식이 다른 text_line 이 있다고 했을때 아래와 같이 실행하면

에러가 출력됩니다.

 

[코드]

text = text_line.split()

print(text)

 

[에러]

AttributeError: 'DataFrame' object has no attribute 'split'

 

[해결]

일반 문자열로 변환 후 처리합니다.

text = str(text_line).split()

print(text)

 

반응형

댓글()

Python 숫자 세자리마다 콤마 입력하기

프로그래밍/Python|2021. 6. 15. 07:46
반응형

[ 소스 ]

number = 1234567
str = "세자리 콤마\n" + str("{0:,}".format(number))
print(str)

 

[ 실행 결과 ]

세자리 콤마
1,234,567

 

 

반응형

댓글()

파이썬에서 텔레그램 메세지 보내기

프로그래밍/Python|2021. 6. 14. 14:17
반응형

사전 준비

# pip install python-telegram-bot --upgrade

 

작성

# vi send.py

import telegram

telegram_token = '1422759215:AAHUr-9IDG2nqz4f7pdVrz0YMA7pAUt9hxs'
bot = telegram.Bot(token = telegram_token)
bot.sendMessage(chat_id = 'xxxxxxxx', text="메세지 내용")

 

* token 생성과 chat_id 확인

텔레그램에서 botfather 검색 후 채팅창에 /newbot 입력, 그 다음 생성할 봇 이름을 입력하면 (예: sysdocu_bot 이렇게 뒤에 _bot 붙여야 함) HTTP API 키가 생성됩니다. (키는 중요하므로 보관합니다)

웹 브라우저에서 발급받은 토큰을 이용해 접근합니다.

URL : https://api.telegram.org/bot1426769915:AAHUr-9IDG2nqz4f9pdVrz0YMA7pAUt9hxs/getUpdates

그다음 botfather 채팅창에 자세히 보면 t.me/sysdocu_bot 이런 형식의 봇 링크가 있습니다. 클릭하고 들어가 /start 라고 입력해줍니다.

또다시 위의 URL 로 접근하면 "id":xxxxxxxx 이런 chat_id 값을 확인 할 수 있습니다.

 

실행

# python send.py

 

이미지와 함께 보내려는 경우 아래와 같이 수정하여 사용하면 됩니다.

 

bot.sendMessage(chat_id='xxxxxxxx', parse_mode='HTML', text="<a href='http://sysdocu.tistory.com/image.png'> </a>메세지 내용")

 

반응형

댓글()