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