for 循环内的 If 语句遍历文件中的行

If statements inside a for loop over lines in a file

我有一个文件data.txt:

./path1
 * WITH LDLDLDLDLDLD                 *
  KDKDKDKDKD
  LDLDLDLDLDLDLDLD
  LDFLFLFLFLFLFLF
['-2.6993']
['-2.6983']
['-2.4490']
  LSLSLSLSLSL
['-2.6993']
['-2.6983']
['-2.4490']
  KKKGKGKGKGKGKGKG
['-79.7549']
  LDLDLDLDLDLDLDLDL
['-126.6208']
['-93.9881']
  KDKDKDKDKDKDKDKD
['-156.9296']
['-135.3548']
  LDLDLDLDDLDDLDLDLD
['-178.3941']
['-162.8602']
['-42.7064']
  KDKDKDKDKDLDLDLDLDLD
['-193.3335']
['-181.9782']
['-68.6555']

./path2
 * WITH DLLDLDLDLDLLDLD                 *
  LDLDLDLDLDLDLD
  BEBEBEBEBEBEL
  LSLSLSLSLSLSL
['-2.6993']
['-2.6983']
['-2.4490']
  OSOSOSOSOSOSOSOS
['-2.6993']
['-2.6983']
['-2.4490']
  KDKDKDKDKDKDKDKDKD
['-156.9296']
['-135.3548']
  MDMDMDMDMDMDDMDM
['-178.3941']
['-162.8602']
['-42.7064']
  KFKFKFKFPKLDLDLD
['-193.3335']
['-181.9782']
['-105.4751']
['-96.2342']

我想从中打印 path 和该路径上的负值。

下面的代码实现了这个目标:

import re
import os
import numpy as np

f = open('data.txt', 'r')
All_aux = []

for line in f:
         if re.match(r"^\.", line):
          print line

         if re.match(r"^\[", line):

                 target2 = line.translate(None, "[]'',")    
                 aux = target2.split()
                 All_aux.append(aux)
                 flat_list = [item for sublist in All_aux for item in sublist]

print 'len(negatives) = ' , len(flat_list)

但是打印出来的信息是这样的:

./path1

./path2

len(negatives) =  32

一旦匹配到第一个if re.match(r"^\.", line):,它就打印该行,但不打印前17个负值。相反,这个值被保存并加到第二条路径上找到的 15 个负值。

我想获得:

./path1

len(negatives) =  17

./path2

len(negatives) =  15

有办法实现吗?

这就是我评论的意思。我还做了一些其他改进,例如使用通常比正则表达式更简单、更高效的字符串方法。

经过与@tripleee 的一些思考和讨论后,我放弃了 flat_list,因为您所做的只是计算长度。

评论了,有不懂的地方请追问:

# None of the imports are required
# We only need a count
negatives = 0

# Previously you were not closing the file
# This closes it automagically
with open('data.txt', 'r') as f:
    for line in f:
        # No need for a regular expression here
        if line.startswith("./"):
            if negatives:
                print 'len(negatives) = ' , negatives, '\n'
                negatives = 0
            print line

        # Used "else if" since both `startswith` can't be true
        elif line.startswith("["):
            target2 = line.translate(None, "[]'',")
            # simplified
            negatives += len(target2.split())

if negatives:
    print 'len(negatives) = ' , negatives

这给出:

./path1

len(negatives) =  17

./path2

len(negatives) =  15