Bài tập python cho mọi người chương 7

Chương 7

bài tập 7. 1

"""
Exercise  7.1: Write a program to read through a file and print the contents
of the file [line by line] all in upper case. Executing the program will look
as follows:

python shout.py
enter a file name: mbox.short.txt
FROM STEPHEN.MARQUARD@UTC.AC.ZA SAT JAN 5 09:14:16 2008
RETURN-PATH: 
RECEIVED: FROM MURDER [MAIL.UMICH.EDU [141.211.14.90]]
    BY FRANKENSTEIN.MAIL.UMICH.EDU [CYRUS V2.3.8] WITH LMTPA;
    SAT, 05 JAN 2008 09:14:16 -0500

You can download the file from
www.py4e.com/code3/mbox-short.txt

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""

# If in a unix-like environment, you can download mbox-short.txt with the
# following command,
# $ curl -O //www.py4e.com/code3/mbox-short.txt
fhand = open['mbox-short.txt']
for line in fhand:                      # Handles one line at a time
    shout = line.rstrip[].upper[]       # Removes newline and capitalizes
    print[shout]
    

bài tập 7. 2

"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    

bài tập 7. 3

"""
Exercise  7.3: Sometimes when programmers get vored or want to have a bit of
fun, they adda harmless Easter Egg to their program. Modify the program that
prompts the user for a file name so that is prints a funny message when the
the user types in the exact file name "na na boo boo". the program should
behave normally for all other files which exist and don't exit. Here is a
sample execution of the program:

python egg.py
Enter the file name: mbox.txt
There were 1797 subject lines in mbox.txt

python egg.py
Enter the file name: missing.tyxt
File cannot be opened: missing.tyxt

python egg.py
Enter the file name: na na boo boo
NA NA BOO BOO TO YOU - You have been punk'd!

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""

fname = input['Enter the file name: ']
try:
    if fname == 'na na boo boo':
        print['NA NA BOO BOO TO YOU - You have been punk\'d!']
        exit[]
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened:', fname]
    exit[]

count = 0
for line in fhand:
    if line.startswith['Subject:']:
        count += 1

print['There were', count, 'subject lines in', fname]
    

Cho đến nay, chúng ta đã học cách viết chương trình và truyền đạt ý định của mình tới Bộ xử lý trung tâm bằng cách sử dụng thực thi có điều kiện, hàm và phép lặp. Chúng ta đã học cách tạo và sử dụng cấu trúc dữ liệu trong Bộ nhớ chính. CPU và bộ nhớ là nơi phần mềm của chúng tôi hoạt động và chạy. Đó là nơi tất cả "suy nghĩ" xảy ra

Nhưng nếu bạn nhớ lại từ các cuộc thảo luận về kiến ​​trúc phần cứng của chúng tôi, sau khi tắt nguồn, mọi thứ được lưu trữ trong CPU hoặc bộ nhớ chính sẽ bị xóa. Vì vậy, cho đến nay, các chương trình của chúng tôi chỉ là những bài tập thú vị thoáng qua để học Python

Bộ nhớ phụ

Trong chương này, chúng ta bắt đầu làm việc với Bộ nhớ phụ [hoặc tệp]. Bộ nhớ phụ không bị xóa khi tắt nguồn. Hoặc trong trường hợp ổ flash USB, dữ liệu chúng tôi ghi từ các chương trình của mình có thể bị xóa khỏi hệ thống và chuyển sang hệ thống khác

Chúng tôi sẽ chủ yếu tập trung vào việc đọc và ghi các tệp văn bản, chẳng hạn như những tệp chúng tôi tạo trong trình soạn thảo văn bản. Sau này chúng ta sẽ xem cách làm việc với tệp cơ sở dữ liệu là tệp nhị phân, được thiết kế đặc biệt để đọc và ghi thông qua phần mềm cơ sở dữ liệu

Khi chúng tôi muốn đọc hoặc ghi một tệp [giả sử trên ổ cứng của bạn], trước tiên chúng tôi phải mở tệp. Mở tệp giao tiếp với hệ điều hành của bạn, biết nơi lưu trữ dữ liệu cho mỗi tệp. Khi bạn mở một tệp, bạn đang yêu cầu hệ điều hành tìm tệp theo tên và đảm bảo rằng tệp tồn tại. Trong ví dụ này, chúng tôi mở tệp

>>> fhand = open['stuff.txt']
Traceback [most recent call last]:
  File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'stuff.txt'
9, tệp này sẽ được lưu trữ trong cùng thư mục mà bạn đang ở khi khởi động Python. Bạn có thể tải tập tin này từ www. py4e. com/code3/mbox. txt

>>> fhand = open['mbox.txt']
>>> print[fhand]

Nếu

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
0 thành công, hệ điều hành sẽ trả về cho chúng tôi một tệp xử lý. Phần xử lý tệp không phải là dữ liệu thực chứa trong tệp mà thay vào đó, nó là một "phần xử lý" mà chúng ta có thể sử dụng để đọc dữ liệu. Bạn được cấp quyền xử lý nếu tệp được yêu cầu tồn tại và bạn có quyền thích hợp để đọc tệp

Xử lý tệp

Nếu tệp không tồn tại, thì

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
0 sẽ không thực hiện truy nguyên được và bạn sẽ không có quyền truy cập vào nội dung của tệp

>>> fhand = open['stuff.txt']
Traceback [most recent call last]:
  File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'stuff.txt'

Sau này, chúng ta sẽ sử dụng

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
2 và
>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
3 để giải quyết tình huống một cách khéo léo hơn khi chúng ta cố mở một tệp không tồn tại

Một tệp văn bản có thể được coi là một chuỗi các dòng, giống như một chuỗi Python có thể được coi là một chuỗi ký tự. Ví dụ: đây là mẫu tệp văn bản ghi lại hoạt động thư từ nhiều cá nhân khác nhau trong nhóm phát triển dự án nguồn mở

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
4
>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
5
>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
6
>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
7
>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
8
>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
9
"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
60
"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
61

Toàn bộ tệp tương tác thư có sẵn từ

www. py4e. com/code3/mbox. txt

và một phiên bản rút gọn của tệp có sẵn từ

www. py4e. com/code3/mbox-ngắn. txt

Các tệp này ở định dạng chuẩn cho một tệp chứa nhiều thư. Các dòng bắt đầu bằng "Từ" phân tách các thư và các dòng bắt đầu bằng "Từ. " là một phần của tin nhắn. Để biết thêm thông tin về định dạng mbox, hãy xem vi. wikipedia. tổ chức/wiki/Mbox

Để chia tệp thành các dòng, có một ký tự đặc biệt đại diện cho "cuối dòng" được gọi là ký tự xuống dòng

Trong Python, chúng tôi biểu thị ký tự xuống dòng dưới dạng dấu gạch chéo ngược-n trong hằng chuỗi. Mặc dù đây trông giống như hai ký tự, nhưng nó thực sự là một ký tự duy nhất. Khi chúng tôi xem xét biến bằng cách nhập "stuff" vào trình thông dịch, nó sẽ hiển thị cho chúng tôi

"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
62 trong chuỗi, nhưng khi chúng tôi sử dụng
"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
63 để hiển thị chuỗi, chúng tôi thấy chuỗi được chia thành hai dòng bởi ký tự xuống dòng

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3

Bạn cũng có thể thấy rằng độ dài của chuỗi

"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
64 là ba ký tự vì ký tự xuống dòng là một ký tự đơn

Vì vậy, khi chúng ta nhìn vào các dòng trong một tệp, chúng ta cần tưởng tượng rằng có một ký tự vô hình đặc biệt được gọi là dòng mới ở cuối mỗi dòng đánh dấu sự kết thúc của dòng đó

Vì vậy, ký tự xuống dòng phân tách các ký tự trong tệp thành các dòng

Mặc dù phần xử lý tệp không chứa dữ liệu cho tệp, nhưng khá dễ dàng để tạo một vòng lặp

"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
65 để đọc qua và đếm từng dòng trong một tệp

Chúng tôi có thể sử dụng trình xử lý tệp làm trình tự trong vòng lặp

"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
65 của chúng tôi. Vòng lặp
"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
65 của chúng tôi chỉ đơn giản là đếm số dòng trong tệp và in chúng ra. Bản dịch sơ bộ của vòng lặp
"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
65 sang tiếng Anh là, "đối với mỗi dòng trong tệp được đại diện bởi phần xử lý tệp, hãy thêm một dòng vào biến
"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
69. "

Lý do hàm

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
0 không đọc toàn bộ tệp là tệp có thể khá lớn với nhiều gigabyte dữ liệu. Câu lệnh
>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
0 mất cùng một lượng thời gian bất kể kích thước của tệp. Vòng lặp
"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
65 thực sự khiến dữ liệu được đọc từ tệp

Khi tệp được đọc bằng vòng lặp

"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
65 theo cách này, Python sẽ xử lý việc chia dữ liệu trong tệp thành các dòng riêng biệt bằng cách sử dụng ký tự xuống dòng. Python đọc từng dòng thông qua dòng mới và bao gồm dòng mới làm ký tự cuối cùng trong biến
>>> fhand = open['stuff.txt']
Traceback [most recent call last]:
  File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'stuff.txt'
14 cho mỗi lần lặp của vòng lặp
"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
65

Bởi vì vòng lặp

"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
65 đọc dữ liệu từng dòng một, nên nó có thể đọc và đếm các dòng trong các tệp rất lớn một cách hiệu quả mà không làm hết bộ nhớ chính để lưu trữ dữ liệu. Chương trình trên có thể đếm các dòng trong bất kỳ tệp có kích thước nào sử dụng rất ít bộ nhớ vì mỗi dòng được đọc, đếm và sau đó bị loại bỏ

Nếu bạn biết tệp tương đối nhỏ so với kích thước của bộ nhớ chính, bạn có thể đọc toàn bộ tệp thành một chuỗi bằng cách sử dụng phương thức

>>> fhand = open['stuff.txt']
Traceback [most recent call last]:
  File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'stuff.txt'
17 trên phần xử lý tệp

"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
6

Trong ví dụ này, toàn bộ nội dung [tất cả 94.626 ký tự] của tệp

>>> fhand = open['stuff.txt']
Traceback [most recent call last]:
  File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'stuff.txt'
18 được đọc trực tiếp vào biến
>>> fhand = open['stuff.txt']
Traceback [most recent call last]:
  File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'stuff.txt'
19. Chúng tôi sử dụng tính năng cắt chuỗi để in ra 20 ký tự đầu tiên của dữ liệu chuỗi được lưu trữ trong
>>> fhand = open['stuff.txt']
Traceback [most recent call last]:
  File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'stuff.txt'
19

Khi tệp được đọc theo cách này, tất cả các ký tự bao gồm tất cả các dòng và ký tự dòng mới là một chuỗi lớn trong biến inp. Hãy nhớ rằng chỉ nên sử dụng dạng hàm

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
0 này nếu dữ liệu tệp vừa với bộ nhớ chính của máy tính của bạn

Nếu tệp quá lớn để vừa với bộ nhớ chính, bạn nên viết chương trình để đọc tệp theo từng đoạn bằng cách sử dụng vòng lặp

"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
65 hoặc
>>> fhand = open['mbox.txt']
>>> print[fhand]
13

Khi bạn đang tìm kiếm thông qua dữ liệu trong một tệp, mẫu rất phổ biến là đọc qua tệp, bỏ qua hầu hết các dòng và chỉ xử lý các dòng đáp ứng một điều kiện cụ thể. Chúng ta có thể kết hợp mẫu để đọc tệp với các phương thức chuỗi để xây dựng các cơ chế tìm kiếm đơn giản

Ví dụ: nếu chúng tôi muốn đọc một tệp và chỉ in ra các dòng bắt đầu bằng tiền tố "Từ. ", chúng ta có thể sử dụng phương thức chuỗi startedwith để chỉ chọn những dòng có tiền tố mong muốn

Khi chương trình này chạy, chúng tôi nhận được đầu ra sau

>>> fhand = open['stuff.txt']
Traceback [most recent call last]:
  File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'stuff.txt'
1

Kết quả đầu ra trông tuyệt vời vì những dòng duy nhất mà chúng ta thấy là những dòng bắt đầu bằng "From. ", nhưng tại sao chúng ta lại thấy các dòng trống thừa? Điều này là do ký tự dòng mới vô hình đó. Mỗi dòng kết thúc bằng một dòng mới, vì vậy câu lệnh

"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
63 in chuỗi trong dòng biến bao gồm một dòng mới và sau đó
"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
63 thêm một dòng mới khác, dẫn đến hiệu ứng giãn cách kép mà chúng ta thấy

Chúng ta có thể sử dụng kỹ thuật cắt dòng để in tất cả trừ ký tự cuối cùng, nhưng một cách tiếp cận đơn giản hơn là sử dụng phương thức rstrip để loại bỏ khoảng trắng ở phía bên phải của chuỗi như sau

Khi chương trình này chạy, chúng tôi nhận được đầu ra sau

>>> fhand = open['mbox.txt']
>>> print[fhand]
1

Khi các chương trình xử lý tệp của bạn trở nên phức tạp hơn, bạn có thể muốn cấu trúc các vòng tìm kiếm của mình bằng cách sử dụng

>>> fhand = open['mbox.txt']
>>> print[fhand]
16. Ý tưởng cơ bản của vòng tìm kiếm là bạn đang tìm kiếm các dòng "thú vị" và bỏ qua các dòng "không thú vị" một cách hiệu quả. Và sau đó khi chúng tôi tìm thấy một dòng thú vị, chúng tôi sẽ làm điều gì đó với dòng đó

Chúng ta có thể cấu trúc vòng lặp theo mô hình bỏ qua các dòng không quan tâm như sau

Đầu ra của chương trình là như nhau. Trong tiếng Anh, những dòng không thú vị là những dòng không bắt đầu bằng "From. ", chúng tôi bỏ qua việc sử dụng

>>> fhand = open['mbox.txt']
>>> print[fhand]
16. Đối với các dòng "thú vị" [tôi. e. , những cái bắt đầu bằng "Từ. "] ta thực hiện xử lý trên các dòng đó

Chúng ta có thể sử dụng phương thức chuỗi

>>> fhand = open['mbox.txt']
>>> print[fhand]
18 để mô phỏng tìm kiếm trong trình soạn thảo văn bản để tìm các dòng có chuỗi tìm kiếm ở bất kỳ đâu trong dòng. Vì
>>> fhand = open['mbox.txt']
>>> print[fhand]
18 tìm kiếm sự xuất hiện của một chuỗi trong một chuỗi khác và trả về vị trí của chuỗi hoặc -1 nếu không tìm thấy chuỗi, chúng ta có thể viết vòng lặp sau để hiển thị các dòng chứa chuỗi "@uct. AC. za" [tôi. e. , họ đến từ Đại học Cape Town ở Nam Phi]

Cái nào tạo ra đầu ra sau

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
0

Chúng tôi thực sự không muốn phải chỉnh sửa mã Python của mình mỗi khi chúng tôi muốn xử lý một tệp khác. Sẽ hữu ích hơn nếu yêu cầu người dùng nhập chuỗi tên tệp mỗi khi chương trình chạy để họ có thể sử dụng chương trình của chúng tôi trên các tệp khác nhau mà không thay đổi mã Python

Điều này khá đơn giản để thực hiện bằng cách đọc tên tệp từ người dùng bằng cách sử dụng

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
00 như sau

Chúng tôi đọc tên tệp từ người dùng và đặt nó vào một biến có tên

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
01 và mở tệp đó. Bây giờ chúng ta có thể chạy chương trình nhiều lần trên các tệp khác nhau

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
3

Trước khi xem qua phần tiếp theo, hãy xem chương trình trên và tự hỏi: "Điều gì có thể xảy ra ở đây?"

Tôi đã bảo bạn đừng nhìn lén. Đây là cơ hội cuối cùng của bạn

Điều gì xảy ra nếu người dùng của chúng tôi nhập một cái gì đó không phải là tên tệp?

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
4

Đừng cười. Người dùng cuối cùng sẽ làm mọi thứ có thể để phá vỡ các chương trình của bạn, dù là có mục đích hay với mục đích xấu. Trên thực tế, một phần quan trọng của bất kỳ nhóm phát triển phần mềm nào là một người hoặc một nhóm được gọi là Đảm bảo chất lượng [hoặc viết tắt là QA] có nhiệm vụ chính là làm những điều điên rồ nhất có thể nhằm phá vỡ phần mềm mà lập trình viên có.

Nhóm QA chịu trách nhiệm tìm ra các lỗi trong chương trình trước khi chúng tôi chuyển giao chương trình cho người dùng cuối, những người có thể mua phần mềm hoặc trả lương cho chúng tôi để viết phần mềm. Vì vậy, nhóm QA là người bạn tốt nhất của lập trình viên

Vì vậy, bây giờ chúng ta đã thấy lỗ hổng trong chương trình, chúng ta có thể sửa nó một cách tao nhã bằng cách sử dụng cấu trúc ________ 52/________ 53. Chúng ta cần giả định rằng cuộc gọi

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
0 có thể bị lỗi và thêm mã khôi phục khi
>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
0 bị lỗi như sau

Hàm

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
06 kết thúc chương trình. Đó là một chức năng mà chúng tôi gọi là không bao giờ trả lại. Giờ đây, khi người dùng của chúng tôi [hoặc nhóm QA] nhập tên tệp sai hoặc ngớ ngẩn, chúng tôi sẽ "bắt" chúng và khôi phục một cách duyên dáng

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
0

Bảo vệ cuộc gọi

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
0 là một ví dụ điển hình về việc sử dụng hợp lý
>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
2 và
>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
3 trong chương trình Python. Chúng tôi sử dụng thuật ngữ "Pythonic" khi chúng tôi đang làm điều gì đó theo "cách Python". Chúng ta có thể nói rằng ví dụ trên là cách Pythonic để mở tệp

Khi bạn trở nên thành thạo hơn về Python, bạn có thể tham gia đối đáp với các lập trình viên Python khác để quyết định giải pháp nào trong số hai giải pháp tương đương cho một vấn đề là "thích Python hơn". Mục tiêu trở nên "Triết học hơn" nắm bắt quan niệm rằng lập trình là một phần kỹ thuật và một phần nghệ thuật. Chúng tôi không phải lúc nào cũng quan tâm đến việc chỉ làm cho một cái gì đó hoạt động, chúng tôi cũng muốn giải pháp của mình trở nên tao nhã và được các đồng nghiệp của chúng tôi đánh giá là tao nhã

Để ghi một tệp, bạn phải mở nó với chế độ "w" làm tham số thứ hai

>>> fhand = open['stuff.txt']
Traceback [most recent call last]:
  File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'stuff.txt'
0

Nếu tệp đã tồn tại, việc mở tệp ở chế độ ghi sẽ xóa dữ liệu cũ và bắt đầu làm mới, vì vậy hãy cẩn thận. Nếu tệp không tồn tại, một tệp mới sẽ được tạo

Phương thức

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
30 của đối tượng xử lý tệp đưa dữ liệu vào tệp, trả về số ký tự đã ghi. Chế độ ghi mặc định là văn bản để viết [và đọc] chuỗi

>>> fhand = open['stuff.txt']
Traceback [most recent call last]:
  File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'stuff.txt'
1

Một lần nữa, đối tượng tệp theo dõi vị trí của nó, vì vậy nếu bạn gọi lại

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
30, nó sẽ thêm dữ liệu mới vào cuối

Chúng ta phải đảm bảo quản lý các đầu dòng khi chúng ta ghi vào tệp bằng cách chèn rõ ràng ký tự xuống dòng khi chúng ta muốn kết thúc một dòng. Câu lệnh

"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
63 tự động thêm một dòng mới, nhưng phương thức
>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
30 không tự động thêm dòng mới

>>> fhand = open['stuff.txt']
Traceback [most recent call last]:
  File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'stuff.txt'
2

Khi bạn ghi xong, bạn phải đóng tệp để đảm bảo rằng bit dữ liệu cuối cùng được ghi vào đĩa một cách vật lý để nó không bị mất nếu mất điện

>>> fhand = open['stuff.txt']
Traceback [most recent call last]:
  File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'stuff.txt'
3

Chúng tôi cũng có thể đóng các tệp mà chúng tôi mở để đọc, nhưng chúng tôi có thể hơi cẩu thả nếu chỉ mở một vài tệp vì Python đảm bảo rằng tất cả các tệp đang mở đều được đóng khi chương trình kết thúc. Khi chúng tôi đang ghi tệp, chúng tôi muốn đóng tệp một cách rõ ràng để không có cơ hội xảy ra

Khi bạn đang đọc và ghi tệp, bạn có thể gặp sự cố với khoảng trắng. Những lỗi này có thể khó gỡ lỗi vì dấu cách, tab và dòng mới thường ẩn

>>> fhand = open['stuff.txt']
Traceback [most recent call last]:
  File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'stuff.txt'
4

Chức năng tích hợp sẵn

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
34 có thể giúp. Nó lấy bất kỳ đối tượng nào làm đối số và trả về một chuỗi biểu diễn đối tượng. Đối với chuỗi, nó đại diện cho các ký tự khoảng trắng với chuỗi dấu gạch chéo ngược

>>> fhand = open['stuff.txt']
Traceback [most recent call last]:
  File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'stuff.txt'
5

Điều này có thể hữu ích để gỡ lỗi

Một vấn đề khác mà bạn có thể gặp phải là các hệ thống khác nhau sử dụng các ký tự khác nhau để biểu thị phần cuối của một dòng. Một số hệ thống sử dụng một dòng mới, đại diện là

"""
Exercise  7.2: Write a program to prompt for a file name, and then read
through the file and look for lines of the form:

X-DSPAM-Confidence:0.8475

When you encounter a line that starts with "X-DSPAM-Confidence:" pull apart
the line to extract the floating-point number on the line. count these lines
and then compute the total of the spam confidence values from these lines.
When you reach the end of the file, print out the average spam confidence.

Enter the file name: mbox.txt
Average spam confidence: 0.894128046745

Enter the file name: mbox-short.txt
Average spam confidence: 0.750718518519

Test your file on the mbox.txt and mbox-short.txt files.

Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance

Solution by Jamison Lahman, May 31, 2017
"""
count = 0                                   # Initialize variables
total = 0

fname = input['Enter the file name: ']
try:
    fhand = open[fname]
except FileNotFoundError:
    print['File cannot be opened: ', fname]
    quit[]

for line in fhand:
    if line.startswith['X-DSPAM-Confidence: ']:
        count = count + 1
        colpos = line.find[':']
        number = line[colpos+1:].strip[]    # Removes all text except number
        SPAM_C = float[number]
        total = total + SPAM_C

average = total / count
print['Average spam confidence: ', average]
    
62. Những người khác sử dụng ký tự trả về, đại diện là
>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
36. Một số sử dụng cả hai. Nếu bạn di chuyển tệp giữa các hệ thống khác nhau, những điểm không nhất quán này có thể gây ra sự cố

Đối với hầu hết các hệ thống, có các ứng dụng để chuyển đổi từ định dạng này sang định dạng khác. Bạn có thể tìm thấy chúng [và đọc thêm về vấn đề này] tại wikipedia. org/wiki/Dòng mới. Hoặc, tất nhiên, bạn có thể tự viết một cái

catchĐể ngăn chặn một ngoại lệ chấm dứt chương trình bằng cách sử dụng các câu lệnh
>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
2 và
>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
3. dòng mớiMột ký tự đặc biệt được sử dụng trong các tệp và chuỗi để chỉ ra phần cuối của một dòng. PythonicMột kỹ thuật hoạt động tinh tế trong Python. "Sử dụng thử và ngoại trừ là cách Pythonic để khôi phục từ các tệp bị thiếu". Người hoặc nhóm Đảm bảo chất lượng tập trung vào việc đảm bảo chất lượng tổng thể của sản phẩm phần mềm. QA thường liên quan đến việc thử nghiệm sản phẩm và xác định các vấn đề trước khi sản phẩm được phát hành. tệp văn bản Chuỗi ký tự được lưu trữ trong bộ lưu trữ vĩnh viễn như ổ cứng

bài tập 1. Viết chương trình đọc qua một tệp và in nội dung của tệp [từng dòng một] tất cả đều viết hoa. Thực thi chương trình sẽ như sau

>>> fhand = open['stuff.txt']
Traceback [most recent call last]:
  File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'stuff.txt'
6

Bạn có thể tải xuống tệp từ

www. py4e. com/code3/mbox-ngắn. txt

Bài tập 2. Viết chương trình nhắc tên tệp, sau đó đọc qua tệp và tìm các dòng có dạng

>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
39
>>> stuff = 'Hello\nWorld!'
>>> stuff
'Hello\nWorld!'
>>> print[stuff]
Hello
World!
>>> stuff = 'X\nY'
>>> print[stuff]
X
Y
>>> len[stuff]
3
40

Khi bạn gặp dòng bắt đầu bằng "X-DSPAM-Confidence. " tách dòng để trích xuất số dấu phẩy động trên dòng. Đếm những dòng này và sau đó tính tổng giá trị độ tin cậy của thư rác từ những dòng này. Khi bạn đọc đến cuối tệp, hãy in ra độ tin cậy thư rác trung bình

>>> fhand = open['stuff.txt']
Traceback [most recent call last]:
  File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'stuff.txt'
7

Kiểm tra tệp của bạn trên các tệp

>>> fhand = open['stuff.txt']
Traceback [most recent call last]:
  File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'stuff.txt'
9 và
>>> fhand = open['stuff.txt']
Traceback [most recent call last]:
  File "", line 1, in 
FileNotFoundError: [Errno 2] No such file or directory: 'stuff.txt'
18

bài tập 3. Đôi khi các lập trình viên cảm thấy buồn chán hoặc muốn giải trí một chút, họ thêm một quả trứng Phục sinh vô hại vào chương trình của họ Sửa đổi chương trình nhắc người dùng nhập tên tệp để chương trình in ra một thông báo vui nhộn khi người dùng nhập đúng tên tệp . Chương trình sẽ hoạt động bình thường đối với tất cả các tệp khác tồn tại và không tồn tại. Đây là một thực hiện mẫu của chương trình

Chủ Đề