Trong hướng dẫn Python này, bạn sẽ học cách tìm kiếm một chuỗi trong một tệp văn bản. Ngoài ra, chúng tôi sẽ thấy cách tìm kiếm một chuỗi trong một tệp và in số dòng và dòng của nó.
Sau khi đọc bài viết này, bạn sẽ học các trường hợp sau.
- Nếu một tệp nhỏ, hãy đọc nó vào một chuỗi và sử dụng phương thức
string exists in a file
2 để kiểm tra xem một chuỗi hoặc từ có có trong một tệp không. [dễ dàng và nhanh hơn so với đọc và kiểm tra dòng trên mỗi dòng] - Nếu một tệp lớn, hãy sử dụng MMAP để tìm kiếm một chuỗi trong một tệp. Chúng tôi không cần phải đọc toàn bộ tệp trong bộ nhớ, điều này sẽ làm cho bộ nhớ giải pháp của chúng tôi hiệu quả.
- Tìm kiếm một chuỗi trong nhiều tệp
- Tìm kiếm tệp cho một danh sách các chuỗi
Chúng tôi sẽ thấy từng giải pháp từng cái một.
Cách tìm kiếm chuỗi trong tệp văn bản
Sử dụng Phương thức Tệp
string exists in a file3 Phương thức và chuỗi chuỗi
string exists in a file2 để tìm kiếm chuỗi trong tệp văn bản. Đây là các bước.
- Mở tệp ở chế độ đọc
Mở tệp bằng cách đặt đường dẫn tệp và chế độ truy cập vào hàm
string exists in a file
5. Chế độ truy cập chỉ định thao tác bạn muốn thực hiện trên tệp, chẳng hạn như đọc hoặc viết. Ví dụ, R là để đọc.string exists in a file
6 - Đọc nội dung từ một tệp
Sau khi mở, hãy đọc tất cả nội dung của một tệp bằng phương thức
string exists in a file
3. Phương thứcstring exists in a file
8 Trả về toàn bộ nội dung tệp ở định dạng chuỗi. - Tìm kiếm một chuỗi trong một tệp
Sử dụng phương thức
string exists in a file
2 của lớp STR để kiểm tra chuỗi hoặc từ đã cho trong kết quả được trả về bằng phương thứcstring exists in a file
3. Phương phápstring exists in a file
2. Phương thức Find [] sẽ trả về -1 nếu văn bản đã cho không có trong một tệp - Dòng in và số dòng
Nếu bạn cần số dòng và dòng, hãy sử dụng phương thức
2] thay vì phương thức# string to search in file word = 'laptop' with open[r'E:\demos\files_demos\account\sales.txt', 'r'] as fp: # read all lines in a list lines = fp.readlines[] for line in lines: # check if string present on a current line if line.find[word] != -1: print[word, 'string exists in file'] print['Line Number:', lines.index[line]] print['Line:', line]
string exists in a file
3. Sử dụng phương thức For Loop và
4 để lặp lại từng dòng từ một tệp. Tiếp theo, trong mỗi lần lặp của một vòng lặp, hãy sử dụng điều kiện IF để kiểm tra xem một chuỗi có mặt trong một dòng hiện tại và in số dòng hiện tại và số dòng# string to search in file word = 'laptop' with open[r'E:\demos\files_demos\account\sales.txt', 'r'] as fp: # read all lines in a list lines = fp.readlines[] for line in lines: # check if string present on a current line if line.find[word] != -1: print[word, 'string exists in file'] print['Line Number:', lines.index[line]] print['Line:', line]
Ví dụ để tìm kiếm một chuỗi trong tệp văn bản
Tôi có một tệp ‘sales.txt, chứa dữ liệu bán hàng hàng tháng của các mặt hàng. Tôi muốn dữ liệu bán hàng của một mặt hàng cụ thể. Hãy cùng xem cách tìm kiếm dữ liệu mục cụ thể trong tệp bán hàng.
def search_str[file_path, word]:
with open[file_path, 'r'] as file:
# read all content of a file
content = file.read[]
# check if string present in a file
if word in content:
print['string exist in a file']
else:
print['string does not exist in a file']
search_str[r'E:\demos\files_demos\account\sales.txt', 'laptop']
Output::
string exists in a file
Tìm kiếm tệp cho một chuỗi và in số dòng và dòng của nó
Sử dụng các bước sau nếu bạn đang tìm kiếm một văn bản cụ thể hoặc một từ trong một tệp và bạn muốn in một số dòng và dòng có mặt.
- Mở một tệp trong chế độ đọc.
- Tiếp theo, sử dụng phương thức
4 để lấy tất cả các dòng từ một tệp dưới dạng đối tượng danh sách.# string to search in file word = 'laptop' with open[r'E:\demos\files_demos\account\sales.txt', 'r'] as fp: # read all lines in a list lines = fp.readlines[] for line in lines: # check if string present on a current line if line.find[word] != -1: print[word, 'string exists in file'] print['Line Number:', lines.index[line]] print['Line:', line]
- Tiếp theo, sử dụng một vòng lặp để lặp từng dòng từ một tệp.
- Tiếp theo, trong mỗi lần lặp của một vòng lặp, sử dụng điều kiện IF để kiểm tra xem một chuỗi có mặt trong một dòng hiện tại và in số dòng và dòng dòng hiện tại.
Ví dụ: Trong ví dụ này, chúng tôi sẽ tìm kiếm chuỗi ‘máy tính xách tay trong một tệp, in dòng của nó cùng với số dòng.: In this example, we’ll search the string ‘laptop’ in a file, print its line along with the line number.
# string to search in file
word = 'laptop'
with open[r'E:\demos\files_demos\account\sales.txt', 'r'] as fp:
# read all lines in a list
lines = fp.readlines[]
for line in lines:
# check if string present on a current line
if line.find[word] != -1:
print[word, 'string exists in file']
print['Line Number:', lines.index[line]]
print['Line:', line]
Output::
laptop string exists in a file line: laptop 10 15000 line number: 1
Lưu ý: Bạn cũng có thể sử dụng phương thức
6 thay vì # string to search in file
word = 'laptop'
with open[r'E:\demos\files_demos\account\sales.txt', 'r'] as fp:
# read all lines in a list
lines = fp.readlines[]
for line in lines:
# check if string present on a current line
if line.find[word] != -1:
print[word, 'string exists in file']
print['Line Number:', lines.index[line]]
print['Line:', line]
7 để đọc từng dòng tệp, hãy dừng lại khi bạn đã đến các dòng bạn muốn. Sử dụng kỹ thuật này, chúng tôi không cần phải đọc toàn bộ tập tin.: You can also use the # string to search in file
word = 'laptop'
with open[r'E:\demos\files_demos\account\sales.txt', 'r'] as fp:
# read all lines in a list
lines = fp.readlines[]
for line in lines:
# check if string present on a current line
if line.find[word] != -1:
print[word, 'string exists in file']
print['Line Number:', lines.index[line]]
print['Line:', line]
# string to search in file
word = 'laptop'
with open[r'E:\demos\files_demos\account\sales.txt', 'r'] as fp:
# read all lines in a list
lines = fp.readlines[]
for line in lines:
# check if string present on a current line
if line.find[word] != -1:
print[word, 'string exists in file']
print['Line Number:', lines.index[line]]
print['Line:', line]
6 method instead of # string to search in file
word = 'laptop'
with open[r'E:\demos\files_demos\account\sales.txt', 'r'] as fp:
# read all lines in a list
lines = fp.readlines[]
for line in lines:
# check if string present on a current line
if line.find[word] != -1:
print[word, 'string exists in file']
print['Line Number:', lines.index[line]]
print['Line:', line]
7 to read a file line by line, stop when you’ve gotten to the lines you want. Using this technique, we don’t need to read the entire file.Cách hiệu quả để tìm kiếm chuỗi trong một tệp văn bản lớn
Tất cả các cách trên đọc toàn bộ tệp trong bộ nhớ. Nếu tệp lớn, đọc toàn bộ tệp trong bộ nhớ là không lý tưởng.
Trong phần này, chúng tôi sẽ thấy cách nhanh nhất và tiết kiệm bộ nhớ nhất để tìm kiếm một chuỗi trong một tệp văn bản lớn.
- Mở tệp ở chế độ đọc
- Sử dụng cho vòng lặp với hàm
8 để có được một dòng và số của nó. Hàm# string to search in file word = 'laptop' with open[r'E:\demos\files_demos\account\sales.txt', 'r'] as fp: # read all lines in a list lines = fp.readlines[] for line in lines: # check if string present on a current line if line.find[word] != -1: print[word, 'string exists in file'] print['Line Number:', lines.index[line]] print['Line:', line]
8 thêm một bộ đếm cho một điều khác nhau và trả về nó trong việc liệt kê đối tượng. Vượt qua con trỏ tệp được trả về bởi hàm# string to search in file word = 'laptop' with open[r'E:\demos\files_demos\account\sales.txt', 'r'] as fp: # read all lines in a list lines = fp.readlines[] for line in lines: # check if string present on a current line if line.find[word] != -1: print[word, 'string exists in file'] print['Line Number:', lines.index[line]] print['Line:', line]
string exists in a file
5 cho
8.# string to search in file word = 'laptop' with open[r'E:\demos\files_demos\account\sales.txt', 'r'] as fp: # read all lines in a list lines = fp.readlines[] for line in lines: # check if string present on a current line if line.find[word] != -1: print[word, 'string exists in file'] print['Line Number:', lines.index[line]] print['Line:', line]
- Chúng ta có thể sử dụng đối tượng liệt kê này với một vòng lặp để truy cập vào từng dòng và số dòng.
Lưu ý: laptop string exists in a file
line: laptop 10 15000
line number: 1
2 không tải toàn bộ tệp trong bộ nhớ, vì vậy đây là một giải pháp hiệu quả.: The
laptop string exists in a file line: laptop 10 15000 line number: 12 doesn’t load the entire file in memory, so this is an efficient solution.
Example::
with open[r"E:\demos\files_demos\account\sales.txt", 'r'] as fp:
for l_no, line in enumerate[fp]:
# search string
if 'laptop' in line:
print['string found in a file']
print['Line Number:', l_no]
print['Line:', line]
# don't look for next lines
break
Example::
string found in a file Line Number: 1 Line: laptop 10 15000
mmap để tìm kiếm một chuỗi trong tệp văn bản
Trong phần này, chúng tôi sẽ thấy cách nhanh nhất và tiết kiệm bộ nhớ nhất để tìm kiếm một chuỗi trong một tệp văn bản lớn.
Mở tệp ở chế độ đọc
Example::
import mmap
with open[r'E:\demos\files_demos\account\sales.txt', 'rb', 0] as file:
s = mmap.mmap[file.fileno[], 0, access=mmap.ACCESS_READ]
if s.find[b'laptop'] != -1:
print['string exist in a file']
Output::
string exist in a file
Sử dụng cho vòng lặp với hàm # string to search in file
word = 'laptop'
with open[r'E:\demos\files_demos\account\sales.txt', 'r'] as fp:
# read all lines in a list
lines = fp.readlines[]
for line in lines:
# check if string present on a current line
if line.find[word] != -1:
print[word, 'string exists in file']
print['Line Number:', lines.index[line]]
print['Line:', line]
8 để có được một dòng và số của nó. Hàm # string to search in file
word = 'laptop'
with open[r'E:\demos\files_demos\account\sales.txt', 'r'] as fp:
# read all lines in a list
lines = fp.readlines[]
for line in lines:
# check if string present on a current line
if line.find[word] != -1:
print[word, 'string exists in file']
print['Line Number:', lines.index[line]]
print['Line:', line]
8 thêm một bộ đếm cho một điều khác nhau và trả về nó trong việc liệt kê đối tượng. Vượt qua con trỏ tệp được trả về bởi hàm string exists in a file
5 cho # string to search in file
word = 'laptop'
with open[r'E:\demos\files_demos\account\sales.txt', 'r'] as fp:
# read all lines in a list
lines = fp.readlines[]
for line in lines:
# check if string present on a current line
if line.find[word] != -1:
print[word, 'string exists in file']
print['Line Number:', lines.index[line]]
print['Line:', line]
8.
# string to search in file
word = 'laptop'
with open[r'E:\demos\files_demos\account\sales.txt', 'r'] as fp:
# read all lines in a list
lines = fp.readlines[]
for line in lines:
# check if string present on a current line
if line.find[word] != -1:
print[word, 'string exists in file']
print['Line Number:', lines.index[line]]
print['Line:', line]
# string to search in file
word = 'laptop'
with open[r'E:\demos\files_demos\account\sales.txt', 'r'] as fp:
# read all lines in a list
lines = fp.readlines[]
for line in lines:
# check if string present on a current line
if line.find[word] != -1:
print[word, 'string exists in file']
print['Line Number:', lines.index[line]]
print['Line:', line]
# string to search in file
word = 'laptop'
with open[r'E:\demos\files_demos\account\sales.txt', 'r'] as fp:
# read all lines in a list
lines = fp.readlines[]
for line in lines:
# check if string present on a current line
if line.find[word] != -1:
print[word, 'string exists in file']
print['Line Number:', lines.index[line]]
print['Line:', line]
Chúng ta có thể sử dụng đối tượng liệt kê này với một vòng lặp để truy cập vào từng dòng và số dòng.
- Lưu ý:
laptop string exists in a file line: laptop 10 15000 line number: 1
2 không tải toàn bộ tệp trong bộ nhớ, vì vậy đây là một giải pháp hiệu quả. - mmap để tìm kiếm một chuỗi trong tệp văn bản
- Ngoài ra, bạn có thể sử dụng mô -đun MMAP để tìm một chuỗi trong một tệp lớn. Phương thức
laptop string exists in a file line: laptop 10 15000 line number: 1
3 tạo đối tượnglaptop string exists in a file line: laptop 10 15000 line number: 1
4 kiểm tra tệp bên dưới thay vì đọc toàn bộ tệp trong bộ nhớ.
Example::
import os
dir_path = r'E:\demos\files_demos\account'
# iterate each file in a directory
for file in os.listdir[dir_path]:
cur_path = os.path.join[dir_path, file]
# check if it is a file
if os.path.isfile[cur_path]:
with open[cur_path, 'r'] as file:
# read all content of a file and search string
if 'laptop' in file.read[]:
print['string found']
break
Output::
string found
Tìm kiếm tệp cho một danh sách các chuỗi
Chúng tôi sẽ thấy từng giải pháp từng cái một.
Example::
string exists in a file0
Output::
string exist in a file
Bài tập và câu đố Python
Các bài tập mã hóa miễn phí và các câu đố bao gồm các vấn đề cơ bản của Python, cấu trúc dữ liệu, phân tích dữ liệu, v.v.
- Hơn 15 bài tập và câu đố dành riêng cho chủ đềTopic-specific Exercises and Quizzes
- Mỗi bài tập chứa 10 câu hỏi
- Mỗi bài kiểm tra chứa 12-15 mcq