Trong hướng dẫn này, chúng ta sẽ học cách Viết chương trình Python để đảo ngược từng từ trong tệp văn bản. Ở đây chúng tôi sẽ sử dụng một tệp có tên secret_societies. txt. Nội dung của tệp được hiển thị bên dưới bằng hình ảnh -
Các bước đảo ngược từng chữ trong file văn bản
- Đầu tiên, chúng tôi sẽ mở tệp ở chế độ “r”, đọc tất cả nội dung và lưu trữ nó trong một biến
- Sau đó, sử dụng phương pháp
split[]
, chúng tôi sẽ tạo một danh sách từ chuỗi - Sau đó, chúng tôi sẽ lặp lại danh sách và đảo ngược từng từ bằng cách cắt
- Sau đó, sử dụng phương pháp
join[]
, chúng tôi sẽ chuyển đổi danh sách thành một chuỗi - Sau đó, chúng tôi sẽ mở tệp ở chế độ “w” và ghi chuỗi vào đó
Viết chương trình Python đảo ngược từng từ trong hội kín. tập tin txt
# opening the file in read mode
with open["secret_societies.txt","r"] as fp:
# creating a list from the string
contents=fp.read[].split[]
# reversing each word[element] of the list
for number in range[len[contents]]:
contents[number]=contents[number][::-1]
# creating a string from the list
contents=[" "].join[contents]
# opening the file in write mode and write the content
with open["secret_societies.txt","w"] as fp:
fp.write[contents]
- Trong đoạn mã trên, đầu tiên chúng tôi đã mở tệp ở chế độ “r”. Sau đó, sử dụng phương pháp
import os def read_reverse_order[file_name]: # Open file for reading in binary mode with open[file_name, 'rb'] as read_obj: # Move the cursor to the end of the file read_obj.seek[0, os.SEEK_END] # Get the current position of pointer i.e eof pointer_location = read_obj.tell[] # Create a buffer to keep the last read line buffer = bytearray[] # Loop till pointer reaches the top of the file while pointer_location >= 0: # Move the file pointer to the location pointed by pointer_location read_obj.seek[pointer_location] # Shift pointer location by -1 pointer_location = pointer_location -1 # read that byte / character new_byte = read_obj.read[1] # If the read byte is new line character then it means one line is read if new_byte == b'\n': # Fetch the line from buffer and yield it yield buffer.decode[][::-1] # Reinitialize the byte array to save next line buffer = bytearray[] else: # If last read character is not eol then add it in buffer buffer.extend[new_byte] # As file is read completely, if there is still data in buffer, then its the first line. if len[buffer] > 0: # Yield the first line too yield buffer.decode[][::-1]
0 vàsplit[]
, chúng tôi đã tạo một danh sách và lưu trữ nó trong biếnimport os def read_reverse_order[file_name]: # Open file for reading in binary mode with open[file_name, 'rb'] as read_obj: # Move the cursor to the end of the file read_obj.seek[0, os.SEEK_END] # Get the current position of pointer i.e eof pointer_location = read_obj.tell[] # Create a buffer to keep the last read line buffer = bytearray[] # Loop till pointer reaches the top of the file while pointer_location >= 0: # Move the file pointer to the location pointed by pointer_location read_obj.seek[pointer_location] # Shift pointer location by -1 pointer_location = pointer_location -1 # read that byte / character new_byte = read_obj.read[1] # If the read byte is new line character then it means one line is read if new_byte == b'\n': # Fetch the line from buffer and yield it yield buffer.decode[][::-1] # Reinitialize the byte array to save next line buffer = bytearray[] else: # If last read character is not eol then add it in buffer buffer.extend[new_byte] # As file is read completely, if there is still data in buffer, then its the first line. if len[buffer] > 0: # Yield the first line too yield buffer.decode[][::-1]
2. Bây giờ giá trị của biến nội dung làimport os def read_reverse_order[file_name]: # Open file for reading in binary mode with open[file_name, 'rb'] as read_obj: # Move the cursor to the end of the file read_obj.seek[0, os.SEEK_END] # Get the current position of pointer i.e eof pointer_location = read_obj.tell[] # Create a buffer to keep the last read line buffer = bytearray[] # Loop till pointer reaches the top of the file while pointer_location >= 0: # Move the file pointer to the location pointed by pointer_location read_obj.seek[pointer_location] # Shift pointer location by -1 pointer_location = pointer_location -1 # read that byte / character new_byte = read_obj.read[1] # If the read byte is new line character then it means one line is read if new_byte == b'\n': # Fetch the line from buffer and yield it yield buffer.decode[][::-1] # Reinitialize the byte array to save next line buffer = bytearray[] else: # If last read character is not eol then add it in buffer buffer.extend[new_byte] # As file is read completely, if there is still data in buffer, then its the first line. if len[buffer] > 0: # Yield the first line too yield buffer.decode[][::-1]
3 - Sau đó, chúng tôi đã lặp lại danh sách và sử dụng Python cắt đảo ngược từng từ trong danh sách. Bây giờ giá trị của biến nội dung là
import os def read_reverse_order[file_name]: # Open file for reading in binary mode with open[file_name, 'rb'] as read_obj: # Move the cursor to the end of the file read_obj.seek[0, os.SEEK_END] # Get the current position of pointer i.e eof pointer_location = read_obj.tell[] # Create a buffer to keep the last read line buffer = bytearray[] # Loop till pointer reaches the top of the file while pointer_location >= 0: # Move the file pointer to the location pointed by pointer_location read_obj.seek[pointer_location] # Shift pointer location by -1 pointer_location = pointer_location -1 # read that byte / character new_byte = read_obj.read[1] # If the read byte is new line character then it means one line is read if new_byte == b'\n': # Fetch the line from buffer and yield it yield buffer.decode[][::-1] # Reinitialize the byte array to save next line buffer = bytearray[] else: # If last read character is not eol then add it in buffer buffer.extend[new_byte] # As file is read completely, if there is still data in buffer, then its the first line. if len[buffer] > 0: # Yield the first line too yield buffer.decode[][::-1]
4 - Bây giờ sử dụng phương pháp
join[]
, chúng tôi đã chuyển đổi danh sách thành một chuỗi - Sau đó, chúng tôi đã mở cùng một tệp ở chế độ “w” và ghi chuỗi vào đó
Cảm ơn bạn đã đọc bài viết này. Nếu bạn thích nó Hãy chia sẻ bài viết. Nếu bạn muốn nói gì hãy Comment
Trong bài viết này, chúng tôi sẽ thảo luận về một giải pháp hiệu quả để đọc nội dung của tệp văn bản hoặc tệp CSV theo thứ tự ngược lại i. e. từng dòng một hoặc lấy chúng dưới dạng danh sách đảo ngược
Đọc từng dòng tệp theo thứ tự đảo ngược bằng python
Một giải pháp hiệu quả để đọc tệp theo thứ tự ngược lại là,
Bắt đầu đọc tệp từ cuối cùng và tiếp tục cho đến khi bắt đầu tệp i. e. theo thứ tự ngược lại. Ngay khi nó gặp bất kỳ '\n' nào thì có nghĩa là một dòng hoàn chỉnh đã được đọc. Sau đó nhường dòng đó và tiếp tục đọc theo hướng ngược lại cho đến khi chạm đến đầu tệp
Chúng tôi đã triển khai logic này cho một chức năng,
import os def read_reverse_order[file_name]: # Open file for reading in binary mode with open[file_name, 'rb'] as read_obj: # Move the cursor to the end of the file read_obj.seek[0, os.SEEK_END] # Get the current position of pointer i.e eof pointer_location = read_obj.tell[] # Create a buffer to keep the last read line buffer = bytearray[] # Loop till pointer reaches the top of the file while pointer_location >= 0: # Move the file pointer to the location pointed by pointer_location read_obj.seek[pointer_location] # Shift pointer location by -1 pointer_location = pointer_location -1 # read that byte / character new_byte = read_obj.read[1] # If the read byte is new line character then it means one line is read if new_byte == b'\n': # Fetch the line from buffer and yield it yield buffer.decode[][::-1] # Reinitialize the byte array to save next line buffer = bytearray[] else: # If last read character is not eol then add it in buffer buffer.extend[new_byte] # As file is read completely, if there is still data in buffer, then its the first line. if len[buffer] > 0: # Yield the first line too yield buffer.decode[][::-1]
Hàm này chấp nhận tên của tệp làm đối số và sau đó tạo ra các dòng tệp từ dưới lên trên
Chức năng này hoạt động như thế nào?
Nó mở tệp ở chế độ đọc nhị phân và di chuyển con trỏ đến cuối tệp bằng tệp. tìm kiếm[]. Sau đó, nó bắt đầu đọc từng byte từ cuối tệp cho đến khi bắt đầu tệp i. e. theo hướng ngược lại và lưu các byte đó vào bộ đệm. Trong khi đọc từng byte, ngay khi nó gặp một ký tự dòng mới '\ n', điều đó có nghĩa là một dòng được đọc thành công. Sau đó, nó đảo ngược bộ đệm và mang lại nội dung của bộ đệm i. e. một dòng hoàn chỉnh. Sau đó, nó khởi tạo lại bộ đệm và tiếp tục đọc các byte tiếp theo từ tệp theo hướng ngược lại cho đến khi đạt đến đầu tệp và tiếp tục tạo ra các dòng cho đến đầu tệp
Hãy sử dụng chức năng này,
Giả sử chúng ta có một tệp 'mẫu. txt’ và nội dung của nó là,
Hello this is a sample file It contains sample text Dummy Line A Dummy Line B Dummy Line C This is the end of file
Đọc nội dung của một 'mẫu. txt’ theo thứ tự đảo ngược từng dòng,
# Iterate over the file in reverse order using for loop for line in read_reverse_order['sample.txt']: print[line]
Đầu ra.
This is the end of file Dummy Line C Dummy Line B Dummy Line A It contains sample text Hello this is a sample file
Vì chúng tôi đang đọc từng byte một và chỉ giữ lại dòng cuối cùng trong bộ đệm, do đó, ngay cả khi tệp lớn, giải pháp của chúng tôi sẽ hiệu quả.
Nhận danh sách tất cả các dòng tệp theo thứ tự đảo ngược bằng python
Thay vì đọc từng dòng một, giả sử chúng ta muốn lấy tất cả các dòng của tệp dưới dạng danh sách nhưng theo thứ tự ngược lại.
Để làm được điều đó, chúng tôi đã tạo một hàm đọc tất cả các dòng của một tệp trong danh sách và sau đó trả về một danh sách đảo ngược,
def read_reverse_order_2[file_name]: """Read a file in reverse order line by line""" # Open file in read mode with open[file_name, 'r'] as read_obj: # get all lines in a file as list lines = read_obj.readlines[] lines = [line.strip[] for line in lines] # reverse the list lines = reversed[lines] # Return the list with all lines of file in reverse order return lines
Hãy sử dụng chức năng này để lấy danh sách đảo ngược tất cả các dòng của tệp 'sample. txt’ rồi lặp lại danh sách đó,
# Get a list of lines in file as reverse order lines_in_reverse_order = read_reverse_order_2['sample.txt'] # iterate over the lines in list for line in lines_in_reverse_order: print[line]
Đầu ra.
This is the end of file Dummy Line C Dummy Line B Dummy Line A It contains sample text Hello this is a sample file
Ở đây chúng tôi có tất cả các dòng của tệp dưới dạng danh sách theo thứ tự ngược lại, sau đó chúng tôi lặp lại danh sách đó.
Nếu bạn chỉ muốn lặp lại các dòng của tệp theo thứ tự ngược lại thì đây không phải là giải pháp hiệu quả, vì nó giữ tất cả các dòng trong bộ nhớ và nếu tệp lớn như tính bằng GB thì nó sẽ tạo ra sự cố. Vì vậy, chỉ sử dụng giải pháp này với các tệp nhỏ và đối với các tệp lớn, hãy ưu tiên giải pháp đầu tiên được đề cập ở trên. Nó hơi phức tạp nhưng chắc chắn là một giải pháp hiệu quả