[英]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.