簡體   English   中英

Python錯誤:“ IndexError:字符串索引超出范圍”

[英]Python error:“IndexError: string index out of range”

我通過使用open將txt文件導入為str

with open('./doc', 'r') as f:
dat = f.readlines()

然后我想使用for循環清除數據

docs = []
for i in dat:
if i.strip()[0] != '<':
    docs.append(i)

錯誤返回

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-131-92a67082e677> in <module>()
      1 docs = []
      2 for i in dat:
----> 3     if i.strip()[0] != '<':
      4         docs.append(i)

IndexError: string index out of range

但是,如果我這樣更改代碼,只需選擇前3000行,代碼就可以工作。

docs = []
for i in dat[:3000]:
if i.strip()[0] != '<':
    docs.append(i)

我的txt文件包含93408行,為什么我不能全部選擇它們? 謝謝!

一行或多行可能是空的,您需要先進行檢查,然后再進行第一個元素

if i.strip() != "" and i.strip()[0] != '<':
    docs.append(i)

暫無
暫無

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

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