Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีสแกนไฟล์สื่อ (Media Files) ใน Python

บทนำ

ในสภาพแวดล้อมธุรกิจจริง ข้อมูลส่วนใหญ่อาจไม่ได้เก็บในไฟล์ text หรือ Excel ฐานข้อมูล SQL เช่น Oracle, SQL Server, PostgreSQL, MySQL ใช้กันอย่างแพร่หลาย และฐานข้อมูลทางเลือกอื่นๆ ก็ยอดนิยม การเลือกฐานข้อมูลขึ้นอยู่กับ performance, data integrity, scalability

ขั้นตอนการทำงาน

ตัวอย่างนี้จะสร้างฐานข้อมูล SQLite3 (มาพร้อม Python ไม่ต้องติดตั้งเพิ่ม) และใช้ Pandas จัดการข้อมูล

1. ตรวจสอบเวอร์ชัน SQLite


import sqlite3
import pandas as pd
print(f"Output \n {sqlite3.version}")

2. สร้าง connection และข้อมูลตัวอย่าง


conn = sqlite3.connect("example.db")

# Customers data
customers = pd.DataFrame({
    "customerID": ["a1", "b1", "c1", "d1"],
    "firstName": ["Person1", "Person2", "Person3", "Person4"],
    "state": ["VIC", "NSW", "QLD", "WA"]
})
print(customers)

# Orders data
orders = pd.DataFrame({
    "customerID": ["a1", "a1", "a1", "d1", "c1", "c1"],
    "productName": ["road bike", "mountain bike", "helmet", "gloves", "road bike", "glasses"]
})
print(orders)

3. เขียนข้อมูลลงฐานข้อมูล


customers.to_sql("customers", con=conn, if_exists="replace", index=False)
orders.to_sql("orders", conn, if_exists="replace", index=False)

4. Query ข้อมูลด้วย SQL


q = """
select orders.customerID, customers.firstName, count(*) as productQuantity
from orders
left join customers on orders.customerID = customers.customerID
group by customers.firstName;
"""
result = pd.read_sql_query(q, con=conn)
print(result)

5. โค้ดรวมทั้งหมด


import sqlite3
import pandas as pd

print(f"Output \n {sqlite3.version}")
conn = sqlite3.connect("example.db")

customers = pd.DataFrame({
    "customerID": ["a1", "b1", "c1", "d1"],
    "firstName": ["Person1", "Person2", "Person3", "Person4"],
    "state": ["VIC", "NSW", "QLD", "WA"]
})
print(f"*** Customers info -\n {customers}")

orders = pd.DataFrame({
    "customerID": ["a1", "a1", "a1", "d1", "c1", "c1"],
    "productName": ["road bike", "mountain bike", "helmet", "gloves", "road bike", "glasses"]
})
print(f"*** Orders info -\n {orders}")

customers.to_sql("customers", con=conn, if_exists="replace", index=False)
orders.to_sql("orders", conn, if_exists="replace", index=False)

q = """
select orders.customerID, customers.firstName, count(*) as productQuantity
from orders
left join customers on orders.customerID = customers.customerID
group by customers.firstName;
"""
pd.read_sql_query(q, con=conn)

ผลลัพธ์


customerID firstName productQuantity
0 a1 Person1 3
1 c1 Person3 2
2 d1 Person4 1

หมายเหตุ: บทความชื่อ "How to scrape through Media Files" แต่เนื้อหาเป็นการใช้ SQLite และ Pandas จัดการข้อมูลลูกค้า/ออเดอร์ ไม่ได้ scrape ไฟล์สื่อ (audio/video/image) จริงๆ