Đảo ngược tệp văn bản python

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ến
    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]
    
    
    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ả

Làm cách nào tôi có thể đảo ngược văn bản Python?

Hàm có sẵn Reverse[] join[] để tạo chuỗi đảo ngược . Tuy nhiên, mục đích chính và trường hợp sử dụng của Reverse[] là hỗ trợ phép lặp ngược trên Python iterables. Với một chuỗi làm đối số, Reverse[] trả về một trình vòng lặp mang lại các ký tự từ chuỗi đầu vào theo thứ tự ngược lại.

Reverse[] có hoạt động trên chuỗi không?

Hãy bắt đầu bằng cách xem phương thức Reverse[] của Python làm gì. Hàm Reverse[] tích hợp sẵn của Python trả về một trình vòng lặp đảo ngược trên các giá trị của một chuỗi đã cho. Đưa ra một chuỗi như any_string , bạn có thể sử dụng phương thức Reverse[] để lấy các ký tự theo thứ tự đảo ngược

Bạn có thể đọc ngược một tệp bằng Python không?

@MichaelDavidWatson. Bạn có thể đọc ngược một tệp mà không cần đọc nó vào bộ nhớ nhưng việc này không cần thiết và yêu cầu nhiều thủ thuật bộ đệm để tránh lãng phí cuộc gọi hệ thống đáng kể. Nó cũng sẽ hoạt động rất tệ [mặc dù tốt hơn là đọc toàn bộ bộ nhớ vào bộ nhớ nếu tệp vượt quá bộ nhớ khả dụng].

Là gì. đảo ngược trong Python?

Trong hướng dẫn này, bạn sẽ tìm hiểu về đảo ngược Python[] với sự trợ giúp của các ví dụ. Phương thức Reverse[] tính toán đảo ngược của một đối tượng chuỗi đã cho và trả về nó ở dạng danh sách .

Chủ Đề