LearnVibeCode
Vibe Coding

Vibe Coding Python: เขียน Python ด้วย AI ให้เร็วกว่าเดิม 5 เท่า

วิรุฬห์ เก่งธัญการ x Claude
#vibe-coding#python#ai-coding#data-science#automation

Vibe Coding Python: เขียน Python ด้วย AI ให้เร็วกว่าเดิม 5 เท่า

Python เป็นภาษาโปรแกรมที่ได้รับความนิยมสูงสุดในโลก และเมื่อรวมกับ Vibe Coding แล้ว คุณจะสามารถพัฒนา Python apps, data analysis, automation, และ AI/ML ได้เร็วและง่ายกว่าที่เคย!

ทำไมต้อง Python + Vibe Coding?

Python เหมาะกับ Vibe Coding มากที่สุด

Python เป็นภาษาที่:

สถิติน่าสนใจ

เตรียมตัวก่อนเริ่ม (10 นาที)

ติดตั้ง Python

Windows:

# ดาวน์โหลดจาก python.org
# หรือใช้ Microsoft Store

# ตรวจสอบ version
python --version

Mac:

# ติดตั้งด้วย Homebrew
brew install python3

# ตรวจสอบ version
python3 --version

Linux:

# Ubuntu/Debian
sudo apt update
sudo apt install python3 python3-pip

# ตรวจสอบ version
python3 --version

ติดตั้ง VS Code Extensions

1. Python (Microsoft) - must have!
2. Pylance - IntelliSense ฉลาด
3. Python Indent - auto-indent ถูกต้อง
4. autoDocstring - สร้าง docstring อัตโนมัติ

ติดตั้ง Essential Libraries

# Virtual environment
python -m venv venv

# Activate (Windows)
venv\Scripts\activate

# Activate (Mac/Linux)
source venv/bin/activate

# ติดตั้ง libraries พื้นฐาน
pip install requests pandas numpy matplotlib jupyter

โปรเจค 1: Web Scraper อัจฉริยะ (30 นาที)

สั่ง AI สร้าง Web Scraper

Prompt:

สร้าง Python web scraper ที่:
1. ดึงข้อมูลข่าวจากเว็บไซต์
2. กรองเฉพาะข่าวที่มีคำว่า "AI" หรือ "Technology"
3. บันทึกลง CSV file
4. มี error handling
5. ใช้ requests และ BeautifulSoup4

ให้โค้ดพร้อมคำอธิบายละเอียด

โค้ดที่ AI สร้างให้:

import requests
from bs4 import BeautifulSoup
import csv
import re
from datetime import datetime
from typing import List, Dict

class NewsScraperAI:
    """
    Web scraper สำหรับดึงข่าว technology และ AI
    """

    def __init__(self, url: str):
        """
        Args:
            url (str): URL ของเว็บไซต์ข่าว
        """
        self.url = url
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        }
        self.keywords = ['AI', 'Technology', 'Machine Learning', 'Data Science']

    def fetch_page(self) -> str:
        """
        ดึงเนื้อหาหน้าเว็บ

        Returns:
            str: HTML content
        """
        try:
            response = requests.get(self.url, headers=self.headers, timeout=10)
            response.raise_for_status()
            return response.text
        except requests.RequestException as e:
            print(f"❌ Error fetching page: {e}")
            return None

    def parse_articles(self, html: str) -> List[Dict]:
        """
        แยกข้อมูลบทความจาก HTML

        Args:
            html (str): HTML content

        Returns:
            List[Dict]: รายการบทความ
        """
        soup = BeautifulSoup(html, 'html.parser')
        articles = []

        # ตัวอย่าง: หา article tags (ปรับตาม structure ของเว็บ)
        article_tags = soup.find_all('article', class_='post')

        for article in article_tags:
            try:
                title = article.find('h2').text.strip()
                link = article.find('a')['href']
                summary = article.find('p', class_='summary')
                summary_text = summary.text.strip() if summary else ''

                # เช็คว่ามี keywords หรือไม่
                if self._contains_keywords(title + ' ' + summary_text):
                    articles.append({
                        'title': title,
                        'link': link,
                        'summary': summary_text,
                        'scraped_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    })
            except (AttributeError, TypeError) as e:
                continue

        return articles

    def _contains_keywords(self, text: str) -> bool:
        """
        เช็คว่าข้อความมี keywords หรือไม่

        Args:
            text (str): ข้อความที่ต้องการเช็ค

        Returns:
            bool: True ถ้ามี keywords
        """
        text_lower = text.lower()
        return any(keyword.lower() in text_lower for keyword in self.keywords)

    def save_to_csv(self, articles: List[Dict], filename: str = 'ai_news.csv'):
        """
        บันทึกข้อมูลลง CSV

        Args:
            articles (List[Dict]): รายการบทความ
            filename (str): ชื่อไฟล์
        """
        if not articles:
            print("⚠️  ไม่มีบทความที่ตรงกับ keywords")
            return

        try:
            with open(filename, 'w', newline='', encoding='utf-8') as f:
                writer = csv.DictWriter(f, fieldnames=articles[0].keys())
                writer.writeheader()
                writer.writerows(articles)

            print(f"✅ บันทึกข้อมูล {len(articles)} บทความลง {filename}")
        except IOError as e:
            print(f"❌ Error saving to CSV: {e}")

    def run(self, output_file: str = 'ai_news.csv'):
        """
        รัน scraper

        Args:
            output_file (str): ชื่อไฟล์ output
        """
        print("🚀 เริ่มดึงข้อมูล...")

        # Fetch page
        html = self.fetch_page()
        if not html:
            return

        # Parse articles
        articles = self.parse_articles(html)
        print(f"📰 พบบทความที่เกี่ยวข้อง: {len(articles)} บทความ")

        # Save to CSV
        self.save_to_csv(articles, output_file)

        # แสดงตัวอย่าง
        if articles:
            print("\n📄 ตัวอย่างบทความแรก:")
            print(f"Title: {articles[0]['title']}")
            print(f"Link: {articles[0]['link']}")


# ตัวอย่างการใช้งาน
if __name__ == "__main__":
    # URL ของเว็บไซต์ (เปลี่ยนเป็น URL จริง)
    URL = "https://example-news-site.com"

    # สร้าง scraper
    scraper = NewsScraperAI(URL)

    # รัน scraper
    scraper.run('ai_tech_news.csv')

ติดตั้ง Libraries ที่ต้องใช้

pip install requests beautifulsoup4 lxml

ปรับแต่งให้เหมาะกับเว็บจริง

Prompt:

ฉันต้องการ scrape ข้อมูลจาก [URL ของเว็บที่ต้องการ]
HTML structure เป็นแบบนี้:
[วาง HTML structure]

ปรับโค้ดให้เหมาะสม

โปรเจค 2: Data Analysis Dashboard (45 นาที)

สร้าง Dashboard วิเคราะห์ข้อมูล

Prompt:

สร้าง Python script สำหรับวิเคราะห์ข้อมูลยอดขาย:

Input: CSV file ที่มี columns: date, product, quantity, price
Output:
1. สรุปยอดขายรวม
2. สินค้าขายดีที่สุด 5 อันดับ
3. กราฟแสดงยอดขายแต่ละเดือน
4. ทำนายยอดขายเดือนหน้า (ใช้ linear regression)

ใช้ pandas, matplotlib, scikit-learn
ให้โค้ดพร้อม sample data

โค้ดที่ได้:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression
import numpy as np
from datetime import datetime, timedelta

class SalesDashboard:
    """
    Dashboard วิเคราะห์ข้อมูลยอดขาย
    """

    def __init__(self, csv_file: str):
        """
        Args:
            csv_file (str): path to CSV file
        """
        self.df = pd.read_csv(csv_file)
        self.df['date'] = pd.to_datetime(self.df['date'])
        self.df['revenue'] = self.df['quantity'] * self.df['price']

        # ตั้งค่า style ของกราฟ
        plt.style.use('seaborn-v0_8-darkgrid')
        sns.set_palette("husl")

    def summary_statistics(self):
        """แสดงสรุปยอดขายรวม"""
        print("=" * 60)
        print("📊 สรุปยอดขายรวม")
        print("=" * 60)

        total_revenue = self.df['revenue'].sum()
        total_quantity = self.df['quantity'].sum()
        avg_price = self.df['price'].mean()
        unique_products = self.df['product'].nunique()

        print(f"💰 รายได้รวม: {total_revenue:,.2f} บาท")
        print(f"📦 จำนวนสินค้าที่ขาย: {total_quantity:,} ชิ้น")
        print(f"💵 ราคาเฉลี่ย: {avg_price:,.2f} บาท")
        print(f"🏷️  จำนวนสินค้าทั้งหมด: {unique_products} ชนิด")
        print()

    def top_products(self, top_n: int = 5):
        """
        แสดงสินค้าขายดี

        Args:
            top_n (int): จำนวนอันดับที่ต้องการ
        """
        print("=" * 60)
        print(f"🏆 สินค้าขายดี TOP {top_n}")
        print("=" * 60)

        top_products = self.df.groupby('product').agg({
            'revenue': 'sum',
            'quantity': 'sum'
        }).sort_values('revenue', ascending=False).head(top_n)

        for i, (product, data) in enumerate(top_products.iterrows(), 1):
            print(f"{i}. {product}")
            print(f"   รายได้: {data['revenue']:,.2f} บาท")
            print(f"   ขายได้: {data['quantity']:,} ชิ้น")
            print()

        return top_products

    def monthly_sales_chart(self):
        """สร้างกราฟยอดขายรายเดือน"""
        # สรุปยอดขายรายเดือน
        self.df['month'] = self.df['date'].dt.to_period('M')
        monthly_sales = self.df.groupby('month')['revenue'].sum()

        # สร้างกราฟ
        plt.figure(figsize=(12, 6))
        monthly_sales.plot(kind='bar', color='skyblue', edgecolor='navy')
        plt.title('📈 ยอดขายรายเดือน', fontsize=16, fontweight='bold')
        plt.xlabel('เดือน', fontsize=12)
        plt.ylabel('รายได้ (บาท)', fontsize=12)
        plt.xticks(rotation=45)
        plt.grid(axis='y', alpha=0.3)

        # ใส่ค่าบนแท่ง
        for i, v in enumerate(monthly_sales):
            plt.text(i, v, f'{v:,.0f}', ha='center', va='bottom')

        plt.tight_layout()
        plt.savefig('monthly_sales.png', dpi=300)
        print("✅ บันทึกกราฟ: monthly_sales.png")
        plt.show()

        return monthly_sales

    def predict_next_month(self):
        """ทำนายยอดขายเดือนหน้า"""
        # เตรียมข้อมูล
        monthly_data = self.df.groupby(
            self.df['date'].dt.to_period('M')
        )['revenue'].sum().reset_index()

        monthly_data['month_number'] = range(1, len(monthly_data) + 1)

        X = monthly_data[['month_number']].values
        y = monthly_data['revenue'].values

        # Train model
        model = LinearRegression()
        model.fit(X, y)

        # ทำนายเดือนหน้า
        next_month = len(monthly_data) + 1
        prediction = model.predict([[next_month]])[0]

        print("=" * 60)
        print("🔮 การทำนายยอดขายเดือนหน้า")
        print("=" * 60)
        print(f"ยอดขายเดือนล่าสุด: {monthly_data['revenue'].iloc[-1]:,.2f} บาท")
        print(f"ยอดขายที่คาดการณ์: {prediction:,.2f} บาท")

        growth_rate = ((prediction - monthly_data['revenue'].iloc[-1]) /
                      monthly_data['revenue'].iloc[-1] * 100)
        print(f"อัตราการเติบโต: {growth_rate:+.2f}%")
        print()

        # สร้างกราฟแสดงการทำนาย
        plt.figure(figsize=(12, 6))
        plt.plot(X, y, marker='o', label='ยอดขายจริง', linewidth=2)
        plt.plot([next_month], [prediction], marker='*', markersize=15,
                color='red', label='ยอดขายที่ทำนาย')

        # เส้น trend
        plt.plot(range(1, next_month + 1),
                model.predict(np.array(range(1, next_month + 1)).reshape(-1, 1)),
                '--', alpha=0.5, label='Trend line')

        plt.title('🔮 การทำนายยอดขาย', fontsize=16, fontweight='bold')
        plt.xlabel('เดือน', fontsize=12)
        plt.ylabel('รายได้ (บาท)', fontsize=12)
        plt.legend()
        plt.grid(True, alpha=0.3)
        plt.tight_layout()
        plt.savefig('sales_prediction.png', dpi=300)
        print("✅ บันทึกกราฟ: sales_prediction.png")
        plt.show()

        return prediction

    def generate_report(self):
        """สร้างรายงานสมบูรณ์"""
        print("\n" + "=" * 60)
        print("📋 SALES ANALYSIS REPORT")
        print("=" * 60 + "\n")

        self.summary_statistics()
        self.top_products()
        self.monthly_sales_chart()
        self.predict_next_month()

        print("=" * 60)
        print("✅ วิเคราะห์ข้อมูลเสร็จสมบูรณ์!")
        print("=" * 60)


# สร้าง sample data
def create_sample_data():
    """สร้างข้อมูลตัวอย่าง"""
    np.random.seed(42)

    dates = pd.date_range(start='2024-01-01', end='2024-12-31', freq='D')
    products = ['iPhone', 'MacBook', 'iPad', 'AirPods', 'Apple Watch',
                'Magic Keyboard', 'Apple Pencil']

    data = []
    for date in dates:
        for _ in range(np.random.randint(5, 15)):
            product = np.random.choice(products)
            quantity = np.random.randint(1, 10)

            # กำหนดราคาตามสินค้า
            prices = {
                'iPhone': 35000,
                'MacBook': 45000,
                'iPad': 25000,
                'AirPods': 5000,
                'Apple Watch': 15000,
                'Magic Keyboard': 4000,
                'Apple Pencil': 3500
            }
            price = prices[product]

            data.append({
                'date': date,
                'product': product,
                'quantity': quantity,
                'price': price
            })

    df = pd.DataFrame(data)
    df.to_csv('sales_data.csv', index=False)
    print("✅ สร้างไฟล์ sales_data.csv สำเร็จ")


# ตัวอย่างการใช้งาน
if __name__ == "__main__":
    # สร้างข้อมูลตัวอย่าง
    create_sample_data()

    # วิเคราะห์ข้อมูล
    dashboard = SalesDashboard('sales_data.csv')
    dashboard.generate_report()

รันโค้ด

# ติดตั้ง libraries
pip install pandas matplotlib seaborn scikit-learn

# รันโปรแกรม
python sales_dashboard.py

โปรเจค 3: Automation Bot (30 นาที)

สร้าง Bot อัตโนมัติ

Prompt:

สร้าง Python automation bot ที่:
1. ส่งรายงานทาง email อัตโนมัติทุกวัน
2. สร้าง PDF report
3. อัปโหลดไฟล์ไป Google Drive
4. Log ทุก activity

ใช้ schedule, smtplib, reportlab, google-api-python-client

โค้ดที่ได้:

import schedule
import time
from datetime import datetime
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
import logging

# ตั้งค่า logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('automation_bot.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)


class AutomationBot:
    """
    Bot อัตโนมัติสำหรับส่งรายงาน
    """

    def __init__(self, smtp_config: dict):
        """
        Args:
            smtp_config (dict): ข้อมูล SMTP configuration
        """
        self.smtp_config = smtp_config

    def generate_pdf_report(self, filename: str = 'daily_report.pdf'):
        """
        สร้าง PDF report

        Args:
            filename (str): ชื่อไฟล์ PDF
        """
        try:
            c = canvas.Canvas(filename, pagesize=letter)
            width, height = letter

            # Header
            c.setFont("Helvetica-Bold", 24)
            c.drawString(100, height - 100, "Daily Report")

            # Date
            c.setFont("Helvetica", 12)
            today = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            c.drawString(100, height - 130, f"Generated: {today}")

            # Content
            c.setFont("Helvetica", 11)
            y_position = height - 180

            content = [
                "📊 Summary Statistics:",
                "- Total Tasks: 47",
                "- Completed: 35",
                "- Pending: 12",
                "",
                "🎯 Top Priorities:",
                "1. Review pull requests",
                "2. Update documentation",
                "3. Deploy to production",
                "",
                "✅ Achievements:",
                "- Fixed 5 critical bugs",
                "- Improved performance by 25%",
                "- Added 3 new features"
            ]

            for line in content:
                c.drawString(100, y_position, line)
                y_position -= 20

            c.save()
            logger.info(f"✅ สร้าง PDF: {filename}")
            return filename

        except Exception as e:
            logger.error(f"❌ Error creating PDF: {e}")
            return None

    def send_email(self, recipient: str, subject: str, body: str,
                   attachment_path: str = None):
        """
        ส่ง email พร้อม attachment

        Args:
            recipient (str): อีเมลผู้รับ
            subject (str): หัวข้อ
            body (str): เนื้อหา
            attachment_path (str): path ของไฟล์แนบ
        """
        try:
            # สร้าง message
            msg = MIMEMultipart()
            msg['From'] = self.smtp_config['email']
            msg['To'] = recipient
            msg['Subject'] = subject

            # เพิ่ม body
            msg.attach(MIMEText(body, 'html'))

            # เพิ่ม attachment
            if attachment_path:
                with open(attachment_path, 'rb') as f:
                    part = MIMEBase('application', 'octet-stream')
                    part.set_payload(f.read())
                    encoders.encode_base64(part)
                    part.add_header(
                        'Content-Disposition',
                        f'attachment; filename={attachment_path}'
                    )
                    msg.attach(part)

            # ส่ง email
            server = smtplib.SMTP(
                self.smtp_config['smtp_server'],
                self.smtp_config['smtp_port']
            )
            server.starttls()
            server.login(
                self.smtp_config['email'],
                self.smtp_config['password']
            )
            server.send_message(msg)
            server.quit()

            logger.info(f"✅ ส่งอีเมลถึง {recipient} สำเร็จ")

        except Exception as e:
            logger.error(f"❌ Error sending email: {e}")

    def daily_task(self):
        """งานที่ต้องทำทุกวัน"""
        logger.info("🚀 เริ่มทำงานประจำวัน...")

        # 1. สร้าง PDF report
        pdf_file = self.generate_pdf_report()

        if pdf_file:
            # 2. ส่ง email
            email_body = f"""
            <html>
                <body>
                    <h2>รายงานประจำวัน</h2>
                    <p>สวัสดีครับ,</p>
                    <p>รายงานประจำวันวันที่ {datetime.now().strftime("%d/%m/%Y")}</p>
                    <p>รายละเอียดในไฟล์แนบครับ</p>
                    <br>
                    <p>ขอแสดงความนับถือ,<br>Automation Bot</p>
                </body>
            </html>
            """

            self.send_email(
                recipient="your-email@example.com",
                subject=f"Daily Report - {datetime.now().strftime('%Y-%m-%d')}",
                body=email_body,
                attachment_path=pdf_file
            )

        logger.info("✅ เสร็จสิ้นงานประจำวัน")

    def start_scheduler(self):
        """เริ่ม scheduler"""
        # กำหนดเวลาทำงาน (ทุกวันเวลา 09:00)
        schedule.every().day.at("09:00").do(self.daily_task)

        logger.info("⏰ Scheduler started - จะส่งรายงานทุกวันเวลา 09:00")

        # ทดสอบส่งทันที (comment out ในการใช้งานจริง)
        # self.daily_task()

        while True:
            schedule.run_pending()
            time.sleep(60)  # เช็คทุก 1 นาที


# ตัวอย่างการใช้งาน
if __name__ == "__main__":
    # SMTP Configuration
    smtp_config = {
        'smtp_server': 'smtp.gmail.com',
        'smtp_port': 587,
        'email': 'your-email@gmail.com',
        'password': 'your-app-password'  # ใช้ App Password, ไม่ใช่รหัสปกติ
    }

    # สร้าง bot
    bot = AutomationBot(smtp_config)

    # เริ่มทำงาน
    bot.start_scheduler()

Vibe Coding Python สำหรับ Data Science

ตัวอย่างการวิเคราะห์ข้อมูล

Prompt:

สร้าง Python script วิเคราะห์ชุดข้อมูล iris:
1. โหลดข้อมูลจาก sklearn
2. สำรวจข้อมูล (EDA)
3. สร้าง visualization 5 แบบ
4. Train ML model (Random Forest)
5. แสดง accuracy และ confusion matrix

ใช้ pandas, matplotlib, seaborn, sklearn

Vibe Coding Python สำหรับ Web Development

สร้าง REST API ด้วย FastAPI

Prompt:

สร้าง REST API ด้วย FastAPI ที่มี:
1. CRUD operations สำหรับ Task
2. User authentication (JWT)
3. Database (SQLite)
4. Auto-generated API docs
5. Input validation

ให้โค้ดพร้อมตัวอย่างการใช้งาน

Best Practices: Python + Vibe Coding

1. Type Hints เสมอ

# ❌ ไม่ดี
def calculate(x, y):
    return x * y

# ✅ ดี
def calculate(x: float, y: float) -> float:
    """คูณตัวเลขสองตัว"""
    return x * y

2. Docstrings ครบถ้วน

def analyze_data(data: pd.DataFrame, column: str) -> dict:
    """
    วิเคราะห์ข้อมูลใน column ที่กำหนด

    Args:
        data (pd.DataFrame): DataFrame ที่ต้องการวิเคราะห์
        column (str): ชื่อ column

    Returns:
        dict: สถิติต่างๆ เช่น mean, median, std

    Raises:
        ValueError: ถ้า column ไม่มีใน DataFrame
    """
    if column not in data.columns:
        raise ValueError(f"Column '{column}' not found")

    return {
        'mean': data[column].mean(),
        'median': data[column].median(),
        'std': data[column].std()
    }

3. Error Handling

def safe_divide(a: float, b: float) -> float:
    """
    หารตัวเลขอย่างปลอดภัย

    Args:
        a (float): ตัวตั้ง
        b (float): ตัวหาร

    Returns:
        float: ผลลัพธ์

    Raises:
        ZeroDivisionError: เมื่อหารด้วย 0
    """
    try:
        return a / b
    except ZeroDivisionError:
        logger.error("Cannot divide by zero")
        raise

4. Virtual Environment

# สร้าง venv
python -m venv venv

# Activate
source venv/bin/activate  # Mac/Linux
venv\Scripts\activate     # Windows

# ติดตั้ง packages
pip install -r requirements.txt

# Save dependencies
pip freeze > requirements.txt

เทคนิคขั้นสูง

1. Async/Await

Prompt:

สร้าง async function ดึงข้อมูลจาก API หลายๆ ตัวพร้อมกัน
ใช้ aiohttp และ asyncio

2. Multiprocessing

Prompt:

สร้างโปรแกรม process ข้อมูลขนาดใหญ่แบบ parallel
ใช้ multiprocessing pool

3. Decorator Pattern

Prompt:

สร้าง decorator สำหรับ:
- Timing function execution
- Logging
- Retry on failure
- Cache results

เส้นทางเรียนรู้ Python + Vibe Coding

Week 1-2: Foundations

Week 3-4: Libraries

Week 5-6: Advanced

Week 7-8: Specialization

เลือก 1 ทาง:

สรุป

Python + Vibe Coding เป็นคู่หูที่ลงตัวสำหรับ:

ข้อดี:

อยากเป็นมือโปร Python? E-book Unlocked Vibe Coding มี:

📚 สั่งซื้อ E-book ที่นี่


ติดต่อเรียน Python + AI:


อ่านบทความอื่นๆ:

← Back to Blog