Computer >> Máy Tính >  >> Lập trình >> Python

Cách đọc tệp văn bản bằng LINECACHE trong Python

Giải pháp ..

Mô-đun bộ đệm dòng thực hiện bộ đệm ẩn chứa nội dung của các tệp, được phân tích cú pháp thành các dòng riêng biệt, trong bộ nhớ. mô-đun linecache trả về dòng / s bằng cách lập chỉ mục vào danh sách và tiết kiệm thời gian khi đọc nhiều lần tệp và phân tích cú pháp các dòng để tìm dòng mong muốn.

mô-đun lincecache rất hữu ích khi tìm kiếm nhiều dòng từ cùng một tệp.

Chuẩn bị dữ liệu thử nghiệm. Bạn có thể nhận được văn bản này chỉ bằng cách sử dụng Google và tìm kiếm văn bản mẫu.

Thành thật mà nói, tôi rất thông minh, lý do là chính xác, và hai điều đó sẽ có lợi khi sử dụng trang web. Để cho Epicurus phát hiện ra hai thứ, hắn cười nhạo cái này kính mới, hắn không muốn sinh ra biển tốt hơn. Hãy để nó đứng để được giải thích với anh ta. Không, nó không bao giờ ngăn cản tôi đi ra biển, nó đã có trên trang web này và nó đã xảy ra. Khi tôi giải tỏa được rắc rối cho anh ấy, tôi sẽ hiểu được những nguy hiểm ở phía bên kia.

Anh ấy tiếp tục làm như vậy một cách thanh lịch. Không có gì phải lo sợ rằng nó dễ dàng kéo ra, nó sẽ là một vẻ đẹp RVing. Vì đó có thể là nỗ lực của người đàn ông, nó dường như là từ những thanh thiếu niên vũ phu, hoặc từ một lý lẽ khác. Hai giác quan ở zril, tôi đồng ý với bất kỳ lực nào khi tôi có thể nhìn vào chúng.

Đối với mỗi khi bạn đã viết một posidon, đừng đồng ý với nó và hãy kiểm tra nó trên thế giới. Democritus thường xúc phạm bạn bằng bạo lực. Để biết liệu nó có nên hoạt động ở sân sau hay không, và bất cứ điều gì bạn không đồng ý hoặc cân nhắc. Nhưng nếu bạn muốn đọc bài đăng, chỉ trích có biển từ các ứng viên chính thống, đừng đặt nặng triết lý bênh vực mật ong. Các chính sách của chúng tôi không được sử dụng.

Cũng không bao giờ nghĩ đến sự đô thị, vì vậy, theo tôi, không có ai mỗi tháng. Hai người đó không bao giờ có thể giúp anh ta. Nghe nói rằng bạn đang bị một cái cây mang theo là tùy thuộc vào bạn, và bạn không muốn bị kéo ra. Tôi không chỉ cần trở nên tốt đẹp mà còn có thể có những bài kiểm tra chính xác. Hãy để tôi trả lời câu hỏi của riêng tôi.

Tuy nhiên, bất cứ lực lượng nào bạn làm là không tương thích. Để cung cấp các mục tiêu của cô ấy cho Hy Lạp. Nếu bạn đang sợ hãi điều gì đó tương tự, một ngày nào đó bạn đang ở ngay trên thế giới. Các bài viết của tôi không phải là ít nhất, từ những câu chuyện đầu tiên của tôi về EU, cho đến vô số vụ bạo lực tế nhị trong phòng xử án. Và ý nghĩa của các từ là gì?

Ví dụ

import os
import tempfile

text = """
Lorem ipsum dolor sit amet, causae apeirian ea his, duo cu congue prodesset. Ut epicuri invenire duo, novum ridens eu has, in natum meliore noluisse sea. Has ei stet explicari. No nam eirmod deterruisset, nusquam electram rationibus ad sea, interesset delicatissimi et sit. Purto molestiae cu eum, in per hinc periculis intellegam.

Id porro facete cum. No est veritus detraxit facilisis, sit ea clita decore essent. Ut eam labores fuisset menandri, ex sit brute viderer eleifend, altera argumentum vel ex. Duo at zril sensibus, eu vim ullum assentior, quando possit at his.

Te nam tempor posidonium scripserit, eam mundi reprimique dissentias ne. Vim te soleat offendit democritum. Nam an diam elaboraret, quaeque dissentias an has. Autem legendos dignissim ad vis, sea ex amet petentium reprehendunt, inermis constituam philosophia ne mel. Esse noster lobortis usu ne.

Nec reque postea urbanitas ut, mea in nulla invidunt ocurreret. Ei duo iuvaret numquam. Ferri nemore audire te est, mel et detracto noluisse. Nec eu habeo justo, id pro posse apeirian volutpat. Mea sonet quaestio ne.

Atqui quaeque alienum te vim. Graeco aliquip liberavisse pro ut. Te similique reformidans usu, te mundi aliquando ius. Meis scripta minimum quo no, meis prima fabellas eu eam, laoreet delicata forensibus ut vim. Et quo vocibus mediocritatem, atqui summo an eam.

"""

1. Tạo một Chức năng để tạo tệp tạm thời và xóa nó sau khi sử dụng.

def make_tempfile():
"""
Function: Create a temporary file.
mkstemp() and mkdtemp() to create temporary files and directories

args: None

return: Temp file name.
"""
fd, temp_file = tempfile.mkstemp()
os.close(fd)

with open(temp_file, 'wt') as f:
f.write(text)

return temp_file

def cleanup(temp_file):
os.unlink(temp_file)

3.Đọc các dòng cụ thể bằng cách sử dụng bộ nhớ đệm. Số dòng của tệp được mô-đun bộ đệm dòng đọc bắt đầu bằng 1, không giống như danh sách bắt đầu lập chỉ mục mảng từ 0. Đây là một điểm quan trọng cần nhớ.

import os
import tempfile
import linecache

text = """
Lorem ipsum dolor sit amet, causae apeirian ea his, duo cu congue prodesset. Ut epicuri invenire duo, novum ridens eu has, in natum meliore noluisse sea. Has ei stet explicari. No nam eirmod deterruisset, nusquam electram rationibus ad sea, interesset delicatissimi et sit. Purto molestiae cu eum, in per hinc periculis intellegam.

Id porro facete cum. No est veritus detraxit facilisis, sit ea clita decore essent. Ut eam labores fuisset menandri, ex sit brute viderer eleifend, altera argumentum vel ex. Duo at zril sensibus, eu vim ullum assentior, quando possit at his.

Te nam tempor posidonium scripserit, eam mundi reprimique dissentias ne. Vim te soleat offendit democritum. Nam an diam elaboraret, quaeque dissentias an has. Autem legendos dignissim ad vis, sea ex amet petentium reprehendunt, inermis constituam philosophia ne mel. Esse noster lobortis usu ne.

Nec reque postea urbanitas ut, mea in nulla invidunt ocurreret. Ei duo iuvaret numquam. Ferri nemore audire te est, mel et detracto noluisse. Nec eu habeo justo, id pro posse apeirian volutpat. Mea sonet quaestio ne.

Atqui quaeque alienum te vim. Graeco aliquip liberavisse pro ut. Te similique reformidans usu, te mundi aliquando ius. Meis scripta minimum quo no, meis prima fabellas eu eam, laoreet delicata forensibus ut vim. Et quo vocibus mediocritatem, atqui summo an eam.
"""

def make_tempfile():
"""
Function: Create a temporary file.
mkstemp() and mkdtemp() to create temporary files and directories

args: None

return: Temp file name.
"""
directory = os.getcwd()
fd, temp_file = tempfile.mkstemp(dir=directory)
os.close(fd)

with open(temp_file, 'wt') as f:
f.write(text)

return temp_file

def cleanup(temp_file):
os.unlink(temp_file)

# Make a file with ipsum data.
filename = make_tempfile()
print(f"Output \n {filename}")

split_line = '\n'

# Pick the lines from source.

print(f"*** Displaying first 5 lines directly from the source \n {text.split(split_line)[4]}" )

# pick out the same line from cache
print(f" \n *** Displaying first 5 lines from the cache \n {linecache.getline(filename, 5)}" )

# cleanup the tempfile by using unlink
cleanup(filename)

Đầu ra

C:\Users\sasan\PycharmProjects\blog\TutorialPoints\Updated_Code\tmpazax_yne
*** Displaying first 5 lines directly from the source
Id porro facete cum. No est veritus detraxit facilisis, sit ea clita decore essent. Ut eam labores fuisset menandri, ex sit brute viderer eleifend, altera argumentum vel ex. Duo at zril sensibus, eu vim ullum assentior, quando possit at his.

*** Displaying first 5 lines from the cache
Id porro facete cum. No est veritus detraxit facilisis, sit ea clita decore essent. Ut eam labores fuisset menandri, ex sit brute viderer eleifend, altera argumentum vel ex. Duo at zril sensibus, eu vim ullum assentior, quando possit at his.

4.Linecache luôn bao gồm dòng mới ở cuối dòng. Do đó, nếu dòng trống, giá trị trả về chỉ là dòng mới.

Xem bên dưới.

import linecache

# Make a file with ipsum data.
filename = make_tempfile()
print(f"Output \n {filename}")

# Blank lines include the newline.

print(f"\n *** The number of lines in the text is 13." )
print(" \n *** Displaying the lastline from Linecache which should be a new line\n {!r}".format(linecache.getline(filename, 8)) )

cleanup(filename)

Đầu ra

C:\Users\sasan\PycharmProjects\blog\TutorialPoints\Updated_Code\tmp352zirvn

*** The number of lines in the text is 13.

*** Displaying the lastline from Linecache which should be a new line
'\n'

5. Kết luận - Khi một ứng dụng cần truy cập ngẫu nhiên vào các tệp, bộ đệm dòng giúp dễ dàng đọc các dòng theo số dòng của chúng. Nội dung của tệp được duy trì trong bộ nhớ cache, vì vậy hãy cẩn thận với việc tiêu thụ bộ nhớ.