Python đọc nhiều dòng

Trong bài viết này, tôi sẽ minh họa nhập liệu nhiều dòng trong ứng dụng Go terminal. Trong bài viết trước, chúng ta đã thảo luận về cách phân tích cú pháp nhiều đầu vào từ người dùng trong Golang. Bây giờ, chúng tôi sẽ giới thiệu 3 phương pháp để đọc nhiều dòng từ bảng điều khiển

  • fmt.Scan[]
  • bufio.Reader[]
  • input text:
    line1
    line2
    line3
    3 lines of text: line1 line2 line3
    0

 

Phương pháp-1. Sử dụng  để đọc nhiều dòng văn bản

input text:
line1
line2
line3
3 lines of text: line1 line2 line3
1. Quét quét văn bản được đọc từ đầu vào tiêu chuẩn, lưu trữ các giá trị được phân tách bằng dấu cách liên tiếp thành các đối số liên tiếp. Dòng mới được tính là khoảng trắng. Nó trả về số lượng mục được quét thành công

Trong ví dụ bên dưới, chúng ta sử dụng hàm

input text:
line1
line2
line3
3 lines of text: line1 line2 line3
2 để đọc 3 dòng từ stdin và lưu mỗi dòng dưới dạng một biến

package main

import [
	"fmt"
	"log"
]

func main[] {
	fmt.Println["input text:"]
	var line1, line2, line3 string
	_, err := fmt.Scan[&line1, &line2, &line3]
	if err != nil {
		log.Fatal[err]
	}

	fmt.Printf["3 lines of text: %s %s %s\n", line1, line2, line3]
}

đầu ra

input text:
line1
line2
line3
3 lines of text: line1 line2 line3

Lưu ý rằng hàm

input text:
line1
line2
line3
3 lines of text: line1 line2 line3
2 coi các dòng mới là khoảng trắng, vì vậy mỗi dòng không được chứa ký tự khoảng trắng

 

CŨNG ĐỌC. Lặp Golang qua Mảng [2 Phương thức]

Phương pháp-2. Sử dụng  để đọc nhiều dòng văn bản

input text:
line1
line2
line3
3 lines of text: line1 line2 line3
4. ReadString đọc cho đến khi xuất hiện dấu phân cách đầu tiên trong đầu vào, trả về một chuỗi chứa dữ liệu cho đến và bao gồm cả dấu phân cách. Nếu ReadString gặp lỗi trước khi tìm thấy dấu phân cách, nó sẽ trả về dữ liệu đã đọc trước lỗi và chính lỗi đó [thường là io. EOF]

Chúng tôi sẽ cho bạn thấy một ví dụ về cách sử dụng

input text:
line1
line2
line3
3 lines of text: line1 line2 line3
5 để nhập nhiều dòng văn bản cho đến khi dòng đó chỉ chứa các ký tự khoảng trắng

________số 8_______

đầu ra

Quảng cáo

input text:
This is GoLinuxCloud
Welcome to our website

output:
This is GoLinuxCloud

Welcome to our website

Lưu ý rằng hàm

input text:
line1
line2
line3
3 lines of text: line1 line2 line3
5 trả về một chuỗi chứa dữ liệu tối đa và bao gồm cả dấu phân cách, vì vậy tất cả các dòng sẽ chứa '
input text:
line1
line2
line3
3 lines of text: line1 line2 line3
7' ở cuối dòng

 

Phương pháp-3. Dùng để đọc nhiều dòng văn bản cho đến dòng trống

input text:
line1
line2
line3
3 lines of text: line1 line2 line3
8. Văn bản trả về mã thông báo gần đây nhất được tạo bởi lệnh gọi Quét dưới dạng một chuỗi mới được phân bổ chứa các byte của nó

CŨNG ĐỌC. Golang io. Ví dụ về ReadCloser

Đây là một ví dụ về việc sử dụng

input text:
line1
line2
line3
3 lines of text: line1 line2 line3
9 để nhập nhiều dòng văn bản cho đến khi dòng nhập trống

package main

import [
	"bufio"
	"fmt"
	"log"
	"os"
]

func main[] {
	fmt.Println["input text:"]
	scanner := bufio.NewScanner[os.Stdin]

	var lines []string
	for {
		scanner.Scan[]
		line := scanner.Text[]

		// break the loop if line is empty
		if len[line] == 0 {
			break
		}
		lines = append[lines, line]
	}

	err := scanner.Err[]
	if err != nil {
		log.Fatal[err]
	}

	fmt.Println["output:"]
	for _, eachLine := range lines {
		fmt.Println[eachLine]
	}
}

đầu ra

input text:
Today is Sunday
Have a nice weekend!

output:
Today is Sunday
Have a nice weekend!

 

Đọc nhiều dòng văn bản từ STDIN có điều kiện

Chúng tôi có thể sửa đổi mã từ Phần 3 để đọc các dòng từ bảng điều khiển và thêm một điều kiện để đọc cho đến khi nó đến một dòng chỉ chứa ký tự 'Q'

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 mà 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ở 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 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
2, đọc một dòng, 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 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 tôi đ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 tôi 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 tôi 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

Chủ Đề