我有一个包含条目的文本文件
***********************
* Row * totalEven *
************************
* 0 * 125000 *
************************
************************
* Row * totalEven *
************************
* 0 * 340000 *
* 1 * 159000 *
************************
************************
* Row * totalEven *
************************
* 0 * 1360000 *
* 1 * 1440000 *
* 2 * 1440000 *
* 3 * 1380000 *
* 4 * 1350000 *
* 5 * 1440000 *
* 6 * 1440000 *
* 7 * 1440000 *
* 8 * 1440000 *
* 9 * 1422000 *
* 10 * 180000 *
它像这样运行了6000多行。我需要从第二栏得到数字,然后把它们加起来。选择这样一条线,我说
f = open(afile,'r')
for i, l in enumerate(f):
if l=="* Row * totalEven *" and (l=='************************'):
continue
else:
nEv = l.split('*')[2] #here it chooses the 2nd column of the line
但是它给了我一个在第三列有数字的输出,空行和带“totalEven”的行。然后我也尝试使用if re.search('* Row * totalEven *', l):
,但它给出了这个错误
Traceback (most recent call last):
File "thecode.py", line 77, in <module>
main()
File "thecode.py", line 45, in main
iArr = getFileValue('rootOut',iArr)
File "thecode.py", line 62, in getFileValue
if re.search('* Row * totalEven *', l):
File "/usr/lib64/python2.6/re.py", line 142, in search
return _compile(pattern, flags).search(string)
File "/usr/lib64/python2.6/re.py", line 245, in _compile
raise error, v # invalid expression
sre_constants.error: nothing to repeat
如有任何建议/解决方案,我将不胜感激。谢谢。你知道吗
您的布尔逻辑不正确:
这怎么能计算成
True
?输入行永远不能同时等于这两个字符串。我想你需要的是or
,而不是and
。也许更好:现在,请注意
[2]
选择第三列,而不是第二列:Python具有基于零的索引。您可以通过选取最后一列来简化:更正
因为在边距上也有列分隔符,所以在列表的每一端都会有一个空字符串,例如
您想要的列是
[2]
或[-2]
。你知道吗在逻辑中发现的缺陷Prune是绝对正确的。你知道吗
但是,如果您想要基于regex的解决方案,就给您。。你知道吗
也试试这个。你知道吗
相关问题 更多 >
编程相关推荐