Đọc đoạn của tập tin python

Một nhiệm vụ phổ biến trong lập trình là mở tệp và phân tích nội dung của nó. Bạn sẽ làm gì khi tệp bạn đang cố xử lý khá lớn, chẳng hạn như vài GB dữ liệu hoặc lớn hơn? . Mặc dù tùy thuộc vào bạn để xác định kích thước phù hợp cho các khối dữ liệu bạn đang xử lý, nhưng đối với nhiều ứng dụng, việc xử lý một tệp tại một thời điểm là phù hợp

Trong suốt bài viết này, chúng tôi sẽ đề cập đến một số ví dụ mã minh họa cách đọc tệp theo từng dòng. Trong trường hợp bạn muốn tự mình thử một số ví dụ này, bạn có thể tìm thấy mã được sử dụng trong bài viết này tại repo GitHub sau

Tệp IO cơ bản trong Python

Python là một ngôn ngữ lập trình có mục đích chung tuyệt vời và nó có một số chức năng IO tệp rất hữu ích trong thư viện tiêu chuẩn gồm các hàm và mô-đun tích hợp sẵn

Chức năng

fp.close()
1 tích hợp là những gì bạn sử dụng để mở một mục đích đọc hoặc viết. Đây là cách bạn có thể sử dụng nó để mở một tập tin

fp = open('path/to/file.txt', 'r')

Như đã trình bày ở trên, hàm

fp.close()
1 nhận nhiều đối số. Chúng tôi sẽ tập trung vào hai đối số, với đối số đầu tiên là tham số chuỗi vị trí biểu thị đường dẫn đến tệp bạn muốn mở. Tham số thứ hai (tùy chọn) cũng là một chuỗi và nó chỉ định chế độ tương tác mà bạn định sử dụng trên đối tượng tệp được trả về bởi lệnh gọi hàm. Các chế độ phổ biến nhất được liệt kê trong bảng bên dưới, với chế độ mặc định là 'r' để đọc

Chế độ Mô tả
fp.close()
3Mở để đọc văn bản thuần túy
fp.close()
4Mở để viết văn bản thuần túy
fp.close()
5Mở một tệp hiện có để nối thêm văn bản thuần túy
fp.close()
6Mở để đọc dữ liệu nhị phân
fp.close()
7Mở để ghi dữ liệu nhị phân

Khi bạn đã viết hoặc đọc tất cả dữ liệu mong muốn trong một đối tượng tệp, bạn cần đóng tệp để tài nguyên có thể được phân bổ lại trên hệ điều hành mà mã đang chạy trên đó

fp.close()

Ghi chú. Việc đóng tài nguyên đối tượng tệp luôn là một phương pháp hay, nhưng đó là một nhiệm vụ rất dễ quên

Mặc dù bạn luôn có thể nhớ gọi

fp.close()
8 trên một đối tượng tệp, nhưng có một cách thay thế và thanh lịch hơn để mở một đối tượng tệp và đảm bảo rằng trình thông dịch Python sẽ dọn sạch sau khi sử dụng

Chỉ đơn giản bằng cách sử dụng từ khóa

fp.close()
9 (được giới thiệu trong Python 2. 5) đối với mã chúng tôi sử dụng để mở một đối tượng tệp, Python sẽ làm điều gì đó tương tự như mã sau. Điều này đảm bảo rằng bất kể đối tượng tệp nào được đóng sau khi sử dụng

Một trong hai phương pháp này đều phù hợp, với ví dụ đầu tiên là Pythonic hơn

Đối tượng tệp được trả về từ hàm

fp.close()
1 có ba phương thức rõ ràng phổ biến (
filepath = 'Iliad.txt'
with open(filepath) as fp:
   line = fp.readline()
   cnt = 1
   while line:
       print("Line {}: {}".format(cnt, line.strip()))
       line = fp.readline()
       cnt += 1
1,
filepath = 'Iliad.txt'
with open(filepath) as fp:
   line = fp.readline()
   cnt = 1
   while line:
       print("Line {}: {}".format(cnt, line.strip()))
       line = fp.readline()
       cnt += 1
2 và
filepath = 'Iliad.txt'
with open(filepath) as fp:
   line = fp.readline()
   cnt = 1
   while line:
       print("Line {}: {}".format(cnt, line.strip()))
       line = fp.readline()
       cnt += 1
3) để đọc dữ liệu. Phương thức
filepath = 'Iliad.txt'
with open(filepath) as fp:
   line = fp.readline()
   cnt = 1
   while line:
       print("Line {}: {}".format(cnt, line.strip()))
       line = fp.readline()
       cnt += 1
1 đọc tất cả dữ liệu thành một chuỗi. Điều này hữu ích cho các tệp nhỏ hơn mà bạn muốn thực hiện thao tác văn bản trên toàn bộ tệp. Sau đó, có
filepath = 'Iliad.txt'
with open(filepath) as fp:
   line = fp.readline()
   cnt = 1
   while line:
       print("Line {}: {}".format(cnt, line.strip()))
       line = fp.readline()
       cnt += 1
2, đây là một cách hữu ích để chỉ đọc từng dòng riêng lẻ, với số lượng tăng dần tại một thời điểm và trả về chúng dưới dạng chuỗi. Phương thức rõ ràng cuối cùng,
filepath = 'Iliad.txt'
with open(filepath) as fp:
   line = fp.readline()
   cnt = 1
   while line:
       print("Line {}: {}".format(cnt, line.strip()))
       line = fp.readline()
       cnt += 1
3, sẽ đọc tất cả các dòng của tệp và trả về chúng dưới dạng danh sách các chuỗi

Ghi chú. Trong phần còn lại của bài viết này, chúng ta sẽ làm việc với văn bản của cuốn sách "Iliad of Homer", có thể tìm thấy tại gutenberg. org, cũng như trong repo GitHub chứa mã cho bài viết này

Đọc từng dòng tệp trong Python với readline()

Hãy bắt đầu với phương thức

filepath = 'Iliad.txt'
with open(filepath) as fp:
   line = fp.readline()
   cnt = 1
   while line:
       print("Line {}: {}".format(cnt, line.strip()))
       line = fp.readline()
       cnt += 1
2, phương thức này đọc một dòng, phương thức này sẽ yêu cầu chúng ta sử dụng bộ đếm và tăng nó

filepath = 'Iliad.txt'
with open(filepath) as fp:
   line = fp.readline()
   cnt = 1
   while line:
       print("Line {}: {}".format(cnt, line.strip()))
       line = fp.readline()
       cnt += 1

Đoạn mã này mở một đối tượng tệp có tham chiếu được lưu trữ trong

filepath = 'Iliad.txt'
with open(filepath) as fp:
   line = fp.readline()
   cnt = 1
   while line:
       print("Line {}: {}".format(cnt, line.strip()))
       line = fp.readline()
       cnt += 1
8, sau đó đọc từng dòng một bằng cách gọi
filepath = 'Iliad.txt'
with open(filepath) as fp:
   line = fp.readline()
   cnt = 1
   while line:
       print("Line {}: {}".format(cnt, line.strip()))
       line = fp.readline()
       cnt += 1
2 trên đối tượng tệp đó lặp đi lặp lại trong một vòng lặp
...
Line 567: exceedingly trifling. We have no remaining inscription earlier than the
Line 568: fortieth Olympiad, and the early inscriptions are rude and unskilfully
Line 569: executed; nor can we even assure ourselves whether Archilochus, Simonides
Line 570: of Amorgus, Kallinus, Tyrtaeus, Xanthus, and the other early elegiac and
Line 571: lyric poets, committed their compositions to writing, or at what time the
Line 572: practice of doing so became familiar. The first positive ground which
Line 573: authorizes us to presume the existence of a manuscript of Homer, is in the
Line 574: famous ordinance of Solon, with regard to the rhapsodies at the
Line 575: Panathenaea: but for what length of time previously manuscripts had
Line 576: existed, we are unable to say.
...
0. Sau đó, nó chỉ cần in dòng ra bàn điều khiển

Chạy mã này, bạn sẽ thấy một cái gì đó như sau

...
Line 567: exceedingly trifling. We have no remaining inscription earlier than the
Line 568: fortieth Olympiad, and the early inscriptions are rude and unskilfully
Line 569: executed; nor can we even assure ourselves whether Archilochus, Simonides
Line 570: of Amorgus, Kallinus, Tyrtaeus, Xanthus, and the other early elegiac and
Line 571: lyric poets, committed their compositions to writing, or at what time the
Line 572: practice of doing so became familiar. The first positive ground which
Line 573: authorizes us to presume the existence of a manuscript of Homer, is in the
Line 574: famous ordinance of Solon, with regard to the rhapsodies at the
Line 575: Panathenaea: but for what length of time previously manuscripts had
Line 576: existed, we are unable to say.
...

Mặc dù, cách tiếp cận này là thô và rõ ràng. Chắc chắn không phải là rất Pythonic. Chúng ta có thể sử dụng phương pháp

filepath = 'Iliad.txt'
with open(filepath) as fp:
   line = fp.readline()
   cnt = 1
   while line:
       print("Line {}: {}".format(cnt, line.strip()))
       line = fp.readline()
       cnt += 1
3 để làm cho mã này ngắn gọn hơn nhiều

Đọc từng dòng tệp với readlines()

Phương thức

filepath = 'Iliad.txt'
with open(filepath) as fp:
   line = fp.readline()
   cnt = 1
   while line:
       print("Line {}: {}".format(cnt, line.strip()))
       line = fp.readline()
       cnt += 1
3 đọc tất cả các dòng và lưu trữ chúng vào một
...
Line 567: exceedingly trifling. We have no remaining inscription earlier than the
Line 568: fortieth Olympiad, and the early inscriptions are rude and unskilfully
Line 569: executed; nor can we even assure ourselves whether Archilochus, Simonides
Line 570: of Amorgus, Kallinus, Tyrtaeus, Xanthus, and the other early elegiac and
Line 571: lyric poets, committed their compositions to writing, or at what time the
Line 572: practice of doing so became familiar. The first positive ground which
Line 573: authorizes us to presume the existence of a manuscript of Homer, is in the
Line 574: famous ordinance of Solon, with regard to the rhapsodies at the
Line 575: Panathenaea: but for what length of time previously manuscripts had
Line 576: existed, we are unable to say.
...
3. Sau đó, chúng tôi có thể lặp lại danh sách đó và sử dụng
...
Line 567: exceedingly trifling. We have no remaining inscription earlier than the
Line 568: fortieth Olympiad, and the early inscriptions are rude and unskilfully
Line 569: executed; nor can we even assure ourselves whether Archilochus, Simonides
Line 570: of Amorgus, Kallinus, Tyrtaeus, Xanthus, and the other early elegiac and
Line 571: lyric poets, committed their compositions to writing, or at what time the
Line 572: practice of doing so became familiar. The first positive ground which
Line 573: authorizes us to presume the existence of a manuscript of Homer, is in the
Line 574: famous ordinance of Solon, with regard to the rhapsodies at the
Line 575: Panathenaea: but for what length of time previously manuscripts had
Line 576: existed, we are unable to say.
...
4, tạo chỉ mục cho mỗi dòng để thuận tiện cho chúng tôi

file = open('Iliad.txt', 'r')
lines = file.readlines()

for index, line in enumerate(lines):
    print("Line {}: {}".format(index, line.strip()))
    
file.close()

Hãy xem hướng dẫn thực hành, thực tế của chúng tôi để học Git, với các phương pháp hay nhất, tiêu chuẩn được ngành chấp nhận và bao gồm bảng gian lận. Dừng các lệnh Git trên Google và thực sự tìm hiểu nó

Kết quả này trong

...
Line 160: INTRODUCTION.
Line 161:
Line 162:
Line 163: Scepticism is as much the result of knowledge, as knowledge is of
Line 164: scepticism. To be content with what we at present know, is, for the most
Line 165: part, to shut our ears against conviction; since, from the very gradual
Line 166: character of our education, we must continually forget, and emancipate
Line 167: ourselves from, knowledge previously acquired; we must set aside old
Line 168: notions and embrace fresh ones; and, as we learn, we must be daily
Line 169: unlearning something which it has cost us no small labour and anxiety to
Line 170: acquire.
...

Bây giờ, mặc dù tốt hơn nhiều, chúng ta thậm chí không cần gọi phương thức

filepath = 'Iliad.txt'
with open(filepath) as fp:
   line = fp.readline()
   cnt = 1
   while line:
       print("Line {}: {}".format(cnt, line.strip()))
       line = fp.readline()
       cnt += 1
3 để đạt được chức năng tương tự. Đây là cách truyền thống để đọc từng dòng một tệp, nhưng có một cách hiện đại hơn, ngắn hơn

Đọc từng dòng tệp bằng vòng lặp for - Cách tiếp cận Pythonic nhất

Bản thân

...
Line 567: exceedingly trifling. We have no remaining inscription earlier than the
Line 568: fortieth Olympiad, and the early inscriptions are rude and unskilfully
Line 569: executed; nor can we even assure ourselves whether Archilochus, Simonides
Line 570: of Amorgus, Kallinus, Tyrtaeus, Xanthus, and the other early elegiac and
Line 571: lyric poets, committed their compositions to writing, or at what time the
Line 572: practice of doing so became familiar. The first positive ground which
Line 573: authorizes us to presume the existence of a manuscript of Homer, is in the
Line 574: famous ordinance of Solon, with regard to the rhapsodies at the
Line 575: Panathenaea: but for what length of time previously manuscripts had
Line 576: existed, we are unable to say.
...
6 được trả về là một lần lặp. Chúng tôi hoàn toàn không cần trích xuất các dòng qua
filepath = 'Iliad.txt'
with open(filepath) as fp:
   line = fp.readline()
   cnt = 1
   while line:
       print("Line {}: {}".format(cnt, line.strip()))
       line = fp.readline()
       cnt += 1
3 - chúng tôi có thể tự lặp lại đối tượng được trả về. Điều này cũng làm cho nó dễ dàng để viết số dòng trong mỗi câu lệnh
...
Line 567: exceedingly trifling. We have no remaining inscription earlier than the
Line 568: fortieth Olympiad, and the early inscriptions are rude and unskilfully
Line 569: executed; nor can we even assure ourselves whether Archilochus, Simonides
Line 570: of Amorgus, Kallinus, Tyrtaeus, Xanthus, and the other early elegiac and
Line 571: lyric poets, committed their compositions to writing, or at what time the
Line 572: practice of doing so became familiar. The first positive ground which
Line 573: authorizes us to presume the existence of a manuscript of Homer, is in the
Line 574: famous ordinance of Solon, with regard to the rhapsodies at the
Line 575: Panathenaea: but for what length of time previously manuscripts had
Line 576: existed, we are unable to say.
...
9

Đây là cách tiếp cận ngắn nhất, Pythonic nhất để giải quyết vấn đề và cách tiếp cận được hầu hết mọi người ưa chuộng.

with open('Iliad.txt') as f:
    for index, line in enumerate(f):
        print("Line {}: {}".format(index, line.strip()))

Kết quả này trong

...
Line 277: Mentes, from Leucadia, the modern Santa Maura, who evinced a knowledge and
Line 278: intelligence rarely found in those times, persuaded Melesigenes to close
Line 279: his school, and accompany him on his travels. He promised not only to pay
Line 280: his expenses, but to furnish him with a further stipend, urging, that,
Line 281: "While he was yet young, it was fitting that he should see with his own
Line 282: eyes the countries and cities which might hereafter be the subjects of his
Line 283: discourses." Melesigenes consented, and set out with his patron,
Line 284: "examining all the curiosities of the countries they visited, and
...

Ở đây, chúng ta đang tận dụng các chức năng tích hợp sẵn của Python cho phép chúng ta lặp lại dễ dàng trên một đối tượng có thể lặp lại, chỉ cần sử dụng vòng lặp

file = open('Iliad.txt', 'r')
lines = file.readlines()

for index, line in enumerate(lines):
    print("Line {}: {}".format(index, line.strip()))
    
file.close()
0. Nếu bạn muốn đọc thêm về các chức năng tích hợp sẵn của Python trên các đối tượng lặp, chúng tôi đã giới thiệu cho bạn

Làm thế nào bạn có thể sử dụng điều này thực tế? . Hầu hết thời gian, sẽ không khôn ngoan nếu đọc toàn bộ kho ngữ liệu vào bộ nhớ. Mặc dù thô sơ, bạn có thể viết một giải pháp từ đầu để đếm tần suất của một số từ nhất định mà không cần sử dụng bất kỳ thư viện bên ngoài nào. Hãy viết một tập lệnh đơn giản tải vào một tệp, đọc từng dòng một và đếm tần suất xuất hiện của các từ, in ra 10 từ thường xuyên nhất và số lần xuất hiện của chúng

import sys
import os

def main():
   filepath = sys.argv[1]
   if not os.path.isfile(filepath):
       print("File path {} does not exist. Exiting...".format(filepath))
       sys.exit()
  
   bag_of_words = {}
   with open(filepath) as fp:
       for line in fp:
           record_word_cnt(line.strip().split(' '), bag_of_words)
   sorted_words = order_bag_of_words(bag_of_words, desc=True)
   print("Most frequent 10 words {}".format(sorted_words[:10]))
  
def order_bag_of_words(bag_of_words, desc=False):
   words = [(word, cnt) for word, cnt in bag_of_words.items()]
   return sorted(words, key=lambda x: x[1], reverse=desc)

def record_word_cnt(words, bag_of_words):
    for word in words:
        if word != '':
            if word.lower() in bag_of_words:
                bag_of_words[word.lower()] += 1
            else:
                bag_of_words[word.lower()] = 1

if __name__ == '__main__':
    main()

Tập lệnh sử dụng mô-đun

file = open('Iliad.txt', 'r')
lines = file.readlines()

for index, line in enumerate(lines):
    print("Line {}: {}".format(index, line.strip()))
    
file.close()
1 để đảm bảo rằng tệp chúng tôi đang cố đọc thực sự tồn tại. Nếu vậy, nó sẽ đọc từng dòng và mỗi dòng được chuyển vào hàm
file = open('Iliad.txt', 'r')
lines = file.readlines()

for index, line in enumerate(lines):
    print("Line {}: {}".format(index, line.strip()))
    
file.close()
2. Nó phân định khoảng trắng giữa các từ và thêm từ đó vào từ điển -
file = open('Iliad.txt', 'r')
lines = file.readlines()

for index, line in enumerate(lines):
    print("Line {}: {}".format(index, line.strip()))
    
file.close()
3. Sau khi tất cả các dòng được ghi vào từ điển, chúng tôi sắp xếp nó qua
file = open('Iliad.txt', 'r')
lines = file.readlines()

for index, line in enumerate(lines):
    print("Line {}: {}".format(index, line.strip()))
    
file.close()
4 trả về danh sách các bộ ở định dạng
file = open('Iliad.txt', 'r')
lines = file.readlines()

for index, line in enumerate(lines):
    print("Line {}: {}".format(index, line.strip()))
    
file.close()
5, được sắp xếp theo số lượng từ

Cuối cùng, chúng tôi in mười từ phổ biến nhất

Thông thường, đối với điều này, bạn sẽ tạo Mô hình Túi từ, sử dụng các thư viện như NLTK, tuy nhiên, việc triển khai này sẽ đủ. Hãy chạy tập lệnh và cung cấp

file = open('Iliad.txt', 'r')
lines = file.readlines()

for index, line in enumerate(lines):
    print("Line {}: {}".format(index, line.strip()))
    
file.close()
6 của chúng ta cho nó

$ python app.py Iliad.txt

Kết quả này trong

fp.close()
0

Phần kết luận

Trong bài viết này, chúng ta đã khám phá nhiều cách để đọc từng dòng một tệp trong Python, cũng như tạo mô hình Túi từ thô sơ để tính toán tần suất của các từ trong một tệp nhất định

Làm cách nào để đọc dữ liệu chunk trong Python?

read_csv() với chunksize . Để kích hoạt chunking, chúng ta sẽ khai báo kích thước của chunk ngay từ đầu. Sau đó, sử dụng read_csv() với tham số chunksize, trả về một đối tượng mà chúng ta có thể lặp lại. Ta chọn chunk size là 50.000 nghĩa là tại một thời điểm chỉ nhập được 50.000 dòng dữ liệu.

Làm cách nào để đọc tệp 10gb bằng Python?

Cách nhanh nhất của Python để đọc tệp văn bản lớn (vài GB) .
# Tài liệu. readline-ví dụ-3. py
tệp = mở ("mẫu. txt")
trong khi 1
dòng = tập tin. đường đọc(100000)
nếu không dòng
phá vỡ
cho dòng trong dòng
vượt qua # làm gì đó**văn bản mạnh**

Làm cách nào để đọc tệp văn bản lớn trong gấu trúc?

GẤU TRÚC .
gấu trúc. read_csv() Đầu vào. Đọc tệp CSV. đầu ra. khung dữ liệu gấu trúc. gấu trúc. read_csv() tải toàn bộ tệp CSV cùng một lúc vào bộ nhớ trong một khung dữ liệu duy nhất. .
gấu trúc. read_csv(chunksize) Đầu vào. Đọc tệp CSV. đầu ra. khung dữ liệu gấu trúc. Thay vì đọc toàn bộ CSV cùng một lúc, các đoạn CSV được đọc vào bộ nhớ