嗨,我有一个关于从我的文本中查找第 # 行并使用此行# 来计算一些东西的快速问题
(这不是硬件问题,我刚开始学习 python)
ex~ 如果我的文字看起来像
100 200 300
400 500 600
700 800 900
120 130 140
150 160 170
和
f1 = open('sample4.txt','r')
line_num = 0
search_phrase = "100"
for line in f1.readlines():
line_num += 1
if line.find(search_phrase) >= 0:
x = line_num
print (x)
import numpy
data = numpy.loadtxt('sample4.txt')
print(data[x:x+3,1].sum())
我可以得到
1430.0 which is (200+500+800+130)
但是,如果我的文字如下所示:
apple is good
i dont like apple
100 200 300
400 500 600
700 800 900
120 130 140
150 160 170
i love orange
错误弹出并说
Traceback (most recent call last):
File "C:/Python33/sample4.py", line 13, in <module>
data = numpy.loadtxt('sample4.txt')
File "C:\Python33\lib\site-packages\numpy\lib\npyio.py", line 827, in loadtxt
items = [conv(val) for (conv, val) in zip(converters, vals)]
File "C:\Python33\lib\site-packages\numpy\lib\npyio.py", line 827, in <listcomp>
items = [conv(val) for (conv, val) in zip(converters, vals)]
ValueError: could not convert string to float: b'apple'
我认为弹出此错误的原因是因为NUMPY
有什么办法可以使这个正确吗?不使用一些skip_header或skip_footer