--------------- <> -----------------
--- KHOA HỌC - CÔNG NGHỆ - GIÁO DỤC - VIỆC LÀM ---
--- Học để đi cùng bà con trên thế giới ---

Tìm kiếm trong Blog

Python (24) - Bài tập thao tác với tập tin văn bản

Bài trước: Python (23) - Thao tác với tập tin văn bản
-----

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

-----
Bài sau:

Math - Grade 1 (2) - Addition 1

Pre: Math - Grade 1 (1) - Identify shapes 1
-----

Unit 2. Addition 1

1.1 Add tens

a. Level 1


10 + 40 = 

30 + 10 = 

20 + 20 =

40 + 30 = 

40 + 40 = 

20 + 30 = 

20 + 50 = 

40 + 20 = 

10 + 30 = 

30 + 30 =


b. Level 2


40 + 50 = 

30 + 50 = 

80 + 10 =

70 + 20 = 

50 + 40 = 

60 + 30 = 

50 + 50 = 

80 + 20 =

30 + 30 = 

90 + 10 = 


c. Level 3


50 + 5 = 

30 + 6 = 

80 + 9 =

8 + 20 = 

22 + 40 = 

16 + 30 = 

10 + 59 = 

80 + 11 =

3 + 30 = 

19 + 10 = 


d. Level 4


15 + 70 = 

3 + 60 = 

78 + 10 =

8 + 20 = 

36 + 60 = 

16 + 30 = 

15 + 80 = 

90 + 7 =

70 + 30 = 

50 + 47 = 

-----
Next:

Python (22) - Kiểu dữ liệu Set

Bài trước: Python (21) - Kiểu dữ liệu Dictionary
-----

22. Kiểu dữ liệu Set

Ở các bài trước, chúng ta đã học về kiểu dữ liệu List (danh sách), kiểu Tuple (bộ) và kiểu Dictionary (từ điển). Bài học này, chúng ta sẽ tìm hiểu về một kiểu dữ liệu nữa, đó là kiểu Set (tập hợp).

22.1 Kiểu dữ liệu Set là gì?

Hãy tưởng tượng, bạn có một chiếc túi đựng các viên bi màu. Trong chiếc túi này:

- Bạn không quan tâm viên bi nào được bỏ vào trước, viên bi nào được bỏ vào sau (không có thứ tự)

- Nếu bạn bỏ hai viên bi màu xanh giống hệt nhau vào, chiếc túi sẽ tự hiểu là chỉ có một viên bi màu xanh (không chứa phần tử trùng lặp)

Trên đây là 2 đặc điểm quan trọng của kiểu dữ liệu Set.

Trong Python, Set được định nghĩa bằng cặp ngoặc nhọn { }, các phần tử cách nhau bởi dấu phẩy.

Ví dụ:

# Khai báo một Set các môn học

mon_hoc = {"Toan", "Van", "Anh", "Toan"}

print(mon_hoc) 

# Kết quả: {'Toan', 'Anh', 'Van'} (Lưu ý: Chữ "Toan" trùng lặp đã bị loại bỏ)

22.2 Truy cập các phần tử trong Set

Vì Set không có thứ tự, nên các phần tử không có số chỉ mục (index) như List. Bạn không thể dùng mon_hoc[0] để lấy phần tử đầu tiên.

Để xem một phần tử có nằm trong Set hay không, chúng ta dùng từ khóa in.

Ví dụ:

mon_hoc = {"Toan", "Van", "Anh"}

print("Toan" in mon_hoc) 

# Kết quả: True

22.3 Thêm phần tử vào Set

Để thêm một phần tử vào Set, chúng ta có thể dùng 2 cách sau:

- add(): Thêm một phần tử

- update(): Thêm nhiều phần tử từ một List hoặc Set khác

Ví dụ:

trai_cay = {"Tao", "Cam"}

trai_cay.add("Xoai") # Thêm 1 quả

trai_cay.update(["Man", "Dao"]) # Thêm nhiều quả

print(trai_cay)

22.4 Xóa phần tử khỏi Set

Bạn có thể lấy phần tử ra khỏi Set bằng 3 cách:

- remove(): Xóa phần tử cụ thể. Nếu phần tử không tồn tại, chương trình sẽ báo lỗi

Ví dụ:

trai_cay = {"Tao", "Cam", "Xoai", "Chuoi"}

# 1. Xóa phần tử có tồn tại trong Set 

trai_cay.remove("Cam") 

print("Set sau khi xoa 'Cam':", hoa_qua) 

# Kết quả: {'Tao', 'Xoai', 'Chuoi'} 

# 2. Xóa phần tử KHÔNG tồn tại trong Set (sẽ phát sinh lỗi KeyError) 

try: trai_cay.remove("Dua hau") 

except KeyError as e: print(f"Lỗi xảy ra: Không tìm thấy phần tử {e} để xóa!") 

- discard(): Xóa phần tử cụ thể. Nếu phần tử không tồn tại, chương trình không báo lỗi

- clear(): Xóa sạch toàn bộ các phần tử trong Set

Ví dụ:

trai_cay = {"Tao", "Cam", "Xoai", "Chuoi"}

trai_cay.clear()

print(trai_cay)

# set rỗng

22.5 Vòng lặp với Set

Dù không có số thứ tự, bạn vẫn có thể dùng vòng lặp for để duyệt qua từng phần tử trong Set.

Ví dụ:

trai_cay = {"Tao", "Cam", "Xoai", "Chuoi"}

for x in trai_cay:

    print(f"Trai cay: {x}")

22.6 Gộp các Set

Bạn có thể sử dụng phương thức union() hoặc update() để gộp 2 Set.

Phương thức union()

Phương thức union() trả về một Set mới, chứa tất cả các phần tử không trùng lặp từ cả hai Set. Hai Set ban đầu vẫn giữ nguyên giá trị.

Ví dụ,

trai_cay1 = {"Cam", "Xoai"}

trai_cay2 = {"Mit", "Xoai", "Bo"}

trai_cay = trai_cay1.union(trai_cay2)

print(trai_cay)

# Cam, Xoai, Mit, Bo

print(trai_cay1)

print(trai_cay2)

Phương thức update()

Phương thức update() sẽ thêm trực tiếp toàn bộ phần tử của Set này vào Set khác. Set gốc sẽ bị thay đổi dữ liệu.

Ví dụ:

trai_cay1 = {"Cam", "Xoai"}

trai_cay2 = {"Mit", "Xoai", "Bo"}

trai_cay1.update(trai_cay2)

print(trai_cay1)

# Cam, Xoai, Mit, Bo

22.7 Frozenset

Frozenset là một kiểu Set đặc biệt. Khi đã tạo một frozenset, bạn không thể thêm, xóa hay sửa đổi các phần tử bên trong nó.

frozenset thường được dùng để định nghĩa một tập hợp các giá trị cố định, giúp bảo vệ dữ liệu tránh vô tình bị thay đổi trong quá trình chạy chương trình.

Ví dụ:

trai_cay1 = frozenset({"Cam", "Xoai"})

trai_cay1.add("Bom")

# Lenh add() se bao loi

22.8 Bài tập và câu hỏi

Bài tập

Bài tập 22a: Bạn đang chuẩn bị một bữa tiệc sinh nhật. Hãy viết đoạn mã quản lý khách mời. Gồm các công việc sau:

- Tạo một Set, đặt tên là khach_moi để chứa tên các khách mời: "Teo", "Ti", "Suu"

- Thêm "Mao" vào khach_moi

- Vì "Ti" bận không đi được, hãy xóa "Ti" khỏi Set

- In ra thông báo: "Có tổng cộng [số lượng] bạn sẽ đến dự tiệc." Gợi ý: Dùng hàm len() để tính số lượng bạn đến dự tiệc.

Bài tập 22b: Kiểm tra thẻ thư viện.

Thư viện trường có một Set các ID thẻ đã đăng ký: {101, 102, 105, 108}

Viết chương trình cho phép bạn nhập một số ID từ bàn phím, sau đó kiểm tra xem ID đó đã có trong hệ thống chưa và in ra thông báo tương ứng.

Bài tập 22c: Lọc phần tử trùng lặp.

Bạn có một danh sách (list) chứa nhiều màu sắc, trong đó có một số màu bị lặp lại: colors = ["do", "xanh", "do", "vang", "xanh"]

Hãy viết mã để biến danh sách này thành một Set để loại bỏ các màu trùng, sau đó in kết quả ra màn hình.

Câu hỏi ôn tập

22.1 Đặc điểm nào sau đây không phải của Set? 

A. Không có thứ tự

B. Có thể chứa các phần tử trùng lặp

C. Được bao bởi dấu { }

D. Có thể thêm phần tử sau khi tạo

22.2 Để thêm một phần tử vào Set, sử dụng phương thức nào? 

A. append()

B. insert()

C. add()

D. update()

22.3 Sự khác biệt giữa setfrozenset là gì? 

A. Set dùng ngoặc nhọn, Frozenset dùng ngoặc vuông

B. Set không cho phép trùng lặp, Frozenset cho phép

C. Set có thể thay đổi dữ liệu, Frozenset thì không

D. Set chỉ chứa số, Frozenset chỉ chứa chữ

22. Set Data Type

In previous lessons, we covered the List, Tuple, and Dictionary data types. In this lesson, we will explore another fundamental data type in Python: the Set.

22.1 What is a Set?

Imagine you have a bag of colored marbles with the following properties:

- Unordered: You do not care which marble was added first or last

- Unique elements: If you put two identical blue marbles into the bag, it automatically treats them as a single blue marble (duplicate values are not stored)

These are the two key characteristics of a Set.

In Python, a Set is defined using curly braces {} with elements separated by commas.

Example:

# Declare a Set of school subjects

subjects = {"Math", "Literature", "English", "Math"}

print(subjects)  

# Output: {'Math', 'English', 'Literature'} (Note: The duplicate 'Math' element was automatically removed)


22.2 Accessing Set Elements

Because Sets are unordered, their elements do not have index numbers like Lists. You cannot use subjects[0] to retrieve the first element.

To check whether an element exists within a Set, use the in keyword.

Example:

subjects = {"Math", "Literature", "English"}

print("Math" in subjects)  

# Output: True

22.3 Adding Elements to a Set

To add elements to a Set, you can use two built-in methods:

- add(): Adds a single element

- update(): Adds multiple elements from an iterable (such as a List or another Set)

Example:

fruits = {"Apple", "Orange"}

fruits.add("Mango")                  # Add a single element

fruits.update(["Plum", "Peach"])     # Add multiple elements

print(fruits)

22.4 Removing Elements from a Set

You can remove elements from a Set using three different methods:

[1] remove(): Removes a specified element. If the element does not exist, it raises a KeyError.

Example:

fruits = {"Apple", "Orange", "Mango", "Banana"}


# 1. Remove an existing element

fruits.remove("Orange")  

print("Set after removing 'Orange':", fruits)  

# Output: {'Apple', 'Mango', 'Banana'}  

# 2. Removing a NON-EXISTENT element (raises a KeyError)

try: 

    fruits.remove("Watermelon")  

except KeyError as e: 

    print(f"Error: Element {e} not found for removal!")  

- [2] discard(): Removes a specified element. If the element does not exist, it does nothing and does not raise an error

- [3] clear(): Removes all elements, leaving an empty Set

Example:

fruits = {"Apple", "Orange", "Mango", "Banana"}

fruits.clear()

print(fruits)

# Output: set() (an empty set)

22.5 Iterating Through a Set

Although Sets lack indexed positions, you can still use a for loop to iterate through each element in a Set.

Example:

fruits = {"Apple", "Orange", "Mango", "Banana"}

for item in fruits:

    print(f"Fruit: {item}")

22.6 Joining Sets

You can merge two Sets using either the union() or update() method.

The union() Method

The union() method returns a new Set containing all unique elements from both original Sets. The original Sets remain unchanged.

Example:

fruits1 = {"Orange", "Mango"}

fruits2 = {"Jackfruit", "Mango", "Avocado"}


all_fruits = fruits1.union(fruits2)

print(all_fruits)   # Output: Orange, Mango, Jackfruit, Avocado

print(fruits1)      # Unchanged

print(fruits2)      # Unchanged

The update() Method

The update() method modifies the original Set in place by inserting all elements from another Set into it.

Example:

fruits1 = {"Orange", "Mango"}

fruits2 = {"Jackfruit", "Mango", "Avocado"}


fruits1.update(fruits2)

print(fruits1)

# Output: Orange, Mango, Jackfruit, Avocado

22.7 Frozenset

A frozenset is an immutable variant of a Set. Once created, its elements cannot be added, removed, or modified.

frozenset is typically used to define fixed collections of values, preventing accidental data modification during execution. Furthermore, because it is immutable and hashable, a frozenset can be used as a Dictionary key or as an element within another Set.

Example:

fruits1 = frozenset({"Orange", "Mango"})

fruits1.add("Apple")

# AttributeError: 'frozenset' object has no attribute 'add'

22.8 Exercises and Review Questions

Exercises

Exercise 22a: You are organizing a birthday party. Write a program to manage your guest list following these steps:

- Create a Set named guest_list containing the names: "Teo", "Ti", "Suu"

- Add "Mao" to guest_list

- Since "Ti" cannot make it, remove "Ti" from the Set

- Print a message: "A total of [number] friends will attend the party." (Hint: Use the len() function to calculate the count)

Exercise 22b: Library Card Validation. A university library maintains a Set of registered card IDs: {101, 102, 105, 108}.

Write a program that prompts the user to enter an ID from the keyboard, checks whether that ID exists in the system, and displays an appropriate message.

Exercise 22c: Filtering Duplicate Elements. You have a List containing various colors, including duplicate entries: colors = ["red", "blue", "red", "yellow", "blue"].

Write code to convert this List into a Set to eliminate duplicate colors, then print the result to the screen.

Review Questions

22.1 Which of the following is NOT a characteristic of a Set?

A. Unordered

B. Can contain duplicate elements

C. Enclosed in curly braces {}

D. Mutable (elements can be added after creation)

22.2 Which method is used to add a single element to a Set?

A. append()

B. insert()

C. add()

D. update()

22.3 What is the difference between a set and a frozenset?

A. set uses curly braces; frozenset uses square brackets.

B. set does not allow duplicates; frozenset allows duplicates.

C. set is mutable; frozenset is immutable.

D. set only contains numbers; frozenset only contains text.

-----
Bài sau: