簡體   English   中英

Python - 從文本文件中提取數據(列表索引超出范圍)

[英]Python - Extracting data from a text file (list index out of range)

我創建了一個腳本來從文本文件(電子郵件數據)中以“發件人:”開頭的行中提取工作日。 我成功地這樣做了,然后作為練習的一部分,我需要修改文本文件,使其導致錯誤。 為此,我在文本文件的第 1 行(下圖)中添加了一個額外的行“From”,這導致原始代碼無法工作並引發錯誤。 為了調試腳本,我添加了一個 if 語句來首先檢查數組的長度是否大於 0 以繼續執行打印語句,盡管這不起作用。 解決此錯誤的最有效方法是什么?

原始代碼:

fhand = open('mbox-short.txt')
count = 0
for line in fhand:
    if line == '': continue
    line = line.rstrip()
    words = line.split()
    if words == []: continue
    if words[0] != 'From' : continue
    print(words[2])

修改的:

修改后的文本文件

代碼:

fhand = open('mbox-short (will fail).txt')
count = 0
for line in fhand:
    if line == '': continue
    line = line.rstrip()
    words = line.split()
    if words == []: continue
    if words[0] != 'From' : continue
    if len(words) >0:
        print(words[2])

OUTPUT:

File "C:\Users\User\Desktop\Chapter 8\8.2 - #2.py", line 9, in <module>
    print(words[2])

IndexError: list index out of range

謝謝 Aditya,問題是列表中存儲了少於 3 個單詞的行(這些不可能包含日期)。 結果,當引用索引 3 時,它拋出了一個錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM