24. Bài tập thao tác với tập tin văn bản
Ở bài học trước, bạn đã được học cách thao tác với tập tin văn bản. Để giúp bạn rèn luyện thêm, bài học này bao gồm các bài tập để bạn thực hành. Làm nhiều thì sẽ quen tay, nghĩ nhiều thì quen não. Bạn hãy tự nghĩ ra cách làm, viết giải thuật ra giấy, và gõ từng dòng mã để giúp nâng cao khả năng tư duy của bạn.
24.1 Thao tác với tập tin .txt
Yêu cầu:
Với mỗi bài tập, bạn bắt buộc phải làm các công việc sau:
- Viết lại các bước của quá trình làm bài, các câu hỏi đã hỏi AI, các câu lệnh lập trình, ý nghĩa của từng câu lệnh (để học về kỹ năng trình bày, tư duy logic, và kỹ năng đặt câu hỏi cho AI)
- Xem phần trình bày mẫu của Bài 24a
Bài 24a: Đếm số từ
Cho tập tin van_ban.txt chứa một đoạn văn tiếng Việt không dấu. Hãy viết chương trình:
- Đọc nội dung từ tập tin
- Đếm xem trong đoạn văn có bao nhiêu từ (các từ cách nhau bằng khoảng trắng)
- Ghi kết quả vào tập tin ket_qua.txt
Các bước thực hiện
[Bước 1] Bạn cần sử dụng chương trình Notepad để tạo tập tin van_ban.txt, nhập nội dung cho tập tin này. Ví dụ, nhập nội dung là: Hoc bai ban > lam chuyen nghiep > song hanh phuc
[Bước 2] Lập trình
- Mở tập tin bằng hàm:
f = open("van_ban.txt", "r", encoding="utf-8")
- Đọc nội dung tập tin, lưu vào một biến, xuất nội dung của biến để kiểm tra xem việc đọc tập tin được chưa?
str = f.read()
print(str)
- Câu hỏi cho AI: trong python, làm sao để đếm số từ của một chuỗi văn bản
- Để đếm từ trong một chuỗi văn bản: sử dụng hàm split() để loại bỏ khoảng trắng thừa và cắt từ dựa trên khoảng trắng, lưu vào danh sách > đếm số phần tử của danh sách bằng hàm len()
words = str.split()
word_count = len(words)
- Xuất kết quả để kiểm tra
print(f"So tu la: {word_count}")
- Ghi kết quả ra tập tin ketqua.txt
(bạn tự làm tiếp ...)
Bài 24b: Tìm số lớn nhất
Cho tập tin day_so.txt gồm nhiều dòng (tối thiểu 10 dòng), mỗi dòng chứa một số nguyên.
- Đọc toàn bộ các số nguyên trong tập tin
- Tìm số lớn nhất và số nhỏ nhất trong dãy số đó
- Ghi dòng chữ "Số lớn nhất là: ..." và "Số nhỏ nhất là: ..." vào tập tin thong_ke.txt
Bài 24c: Kiểm tra số nguyên tố
Cho tập tin input.txt chứa một số nguyên dương n
- Đọc giá trị n từ tập tin
- Kiểm tra xem n có phải là số nguyên tố hay không
- Nếu là số nguyên tố, ghi "YES" vào tập tin output.txt. Ngược lại ghi "NO"
24.2 Bài tập về tập tin CSV
Tập tin CSV thường được dùng để quản lý danh sách có cấu trúc cột rõ ràng, giống như quản lý học sinh hoặc kho hàng.
Bài 24d: Quản lý thư viện
Tạo danh sách gồm 3 cuốn sách bạn yêu thích (Tên sách, Tác giả).
- Ghi danh sách này vào tập tin thu_vien.csv
- Viết chương trình đọc lại tập tin này và in ra màn hình theo định dạng: "Cuốn sách [Tên sách] được viết bởi [Tác giả]".
Bài 24e: Tính điểm trung bình
Cho tập tin bang_diem.csv có cấu trúc: Tên,Toán,Văn.
Ví dụ:
[bang_diem.csv]
Tên,Toán,Văn
Nguyen Van An,8,9
Le Thi Binh,10,7
Tran Huu Loc,6.5,8
- Đọc dữ liệu từ tập tin
- Tính điểm trung bình (ĐTB = (Toán + Văn) / 2) cho từng học sinh
- Ghi thêm một cột "Trung Bình" vào tập tin mới đặt tên là ket_qua_hoc_tap.csv.
Bài 24f: Lọc dữ liệu
Cho tập tin san_pham.csv chứa danh sách hàng hóa: Tên SP,Giá Tiền.
Ví dụ:
[san_pham.csv]
Tên SP,Giá Tiền
Chuột máy tính,250000
Bàn phím cơ,850000
Tai nghe,450000
Lót chuột,100000
Loa Bluetooth,1200000
- Viết chương trình yêu cầu người dùng nhập vào một mức giá ngân sách (ví dụ: 500.000)
- Tìm và liệt kê tất cả các sản phẩm có giá thấp hơn hoặc bằng mức ngân sách đó
- Lưu danh sách các sản phẩm thỏa mãn vào tập tin mua_sam.csv
24. Exercise with Text Files
In the previous lesson, you learned how to work with text files. To help you practice further, this lesson includes hands-on exercises. Practice builds muscle memory, and active thinking sharpens the mind. Try to figure out the solutions on your own, write the algorithms on paper, and type out every line of code to enhance your computational thinking skills.
24.1 Working with .txt Files
Requirements
For every exercise, you must complete the following steps:
- Document your step-by-step process, the prompts/questions you asked AI, the code snippets, and the explanation of each line of code (to develop documentation skills, logical reasoning, and effective AI prompting skills)
- Refer to the sample layout in Task 24a
Task 24a: Word Count
Given a file named van_ban.txt containing unaccented Vietnamese text, write a program to:
- Read the content from the file
- Count the total number of words in the text (words are separated by spaces)
- Write the output to a file named ket_qua.txt
Execution Steps
[Step 1]: Use Notepad (or any text editor) to create van_ban.txt and enter sample content.
Example content: Hoc bai ban > lam chuyen nghiep > song hanh phuc
[Step 2]: Coding
- Open the file using:
f = open("van_ban.txt", "r", encoding="utf-8")
- Read the file content into a variable and print it out to verify the file reading step:
str = f.read()
print(str)
- Prompt asked the AI: "How to count the number of words in a text string in Python?"
- Use the split() method to strip excess whitespace and split the string into words based on spaces, storing them in a list. Then, count the number of elements using len().
words = str.split()
word_count = len(words)
- Output the result:
print(f"So tu la: {word_count}")
- Write the results to the ketqua.txt file
(Complete the rest on your own...)
Task 24b: Find Maximum and Minimum
Given a file named day_so.txt with multiple lines (at least 10 lines), where each line contains an integer:
- Read all integers from the file
- Find the maximum and minimum values in the dataset
- Write "The maximum value is:...” and "The minimum value is: …” to a file named thong_ke.txt
Task 24c: Prime Number Check
Given a file named input.txt containing a positive integer n:
- Read the value of n from the file
- Check whether n is a prime number
- If it is a prime number, write "YES" to output.txt. Otherwise, write "NO"
24.2 CSV File Exercises
CSV files are commonly used to handle structured tabular data, such as student records or inventory management.
Task 24d: Library Management
Create a list containing 3 of your favorite books (Book Title, Author)
- Export/write this list to a file named thu_vien.csv
- Write a program to read this file back and display the output in the format:
"The book [Book Title] was written by [Author]”
Task 24e: Calculate Average Score
Given a file named bang_diem.csv with the structure: Name, Math, Literature.
Example (bang_diem.csv):
Name, Math, Literature
Nguyen Van An, 8, 9
Le Thi Binh, 10, 7
Tran Huu Loc, 6.5, 8
- Read data from the file
- Calculate the average score GPA = (Math + Literature)/2 for each student
- Append a new column named "Average" and save the output to a new file named ket_qua_hoc_tap.csv.
Task 24f: Data Filtering
Given a file named san_pham.csv containing a product inventory list: Product Name, Price.
Example (san_pham.csv):
Product Name, Price
Computer Mouse, 250000
Mechanical Keyboard, 850000
Headphones, 450000
Mousepad, 100000
Bluetooth Speaker, 1200000
- Write a program that prompts the user to enter a budget limit (e.g., 500000)
- Filter and display all products with a price less than or equal to the entered budget
- Save the filtered result set into a file named mua_sam.csv