3

我是 python 新手,正在编写一个程序来计算行数。该文件如下所示:

  0.86149806
  1.8628227
 -0.1380086
 -1
  0.99927421
 -1.0007207
  0.99927421
  0.99926955
  -1.0007258

我的代码尝试如下:

counterPos = 0
counterNeg = 0
counterTot = 0
counterNeu = 0
with open('test.txt', 'r') as infile:
    for line in infile:
        counterTot += 1
        for i in line:
            if i > 0.3:
                counterPos += 1
            elif i < -0.3:
                counterNeg += 1
            else:
                counterNeu += 1

我试图让它计算所有低于 -0.3 到counterNeg的行,所有高于 0.3 的行counterPos,以及所有数字在 0.29 到 -0.29 到 之间的行counterNeu

虽然它似乎不起作用,我知道我错了,for i in line但不知道怎么做。

4

3 回答 3

6

line是一个字符串,但您想将其解析为float. 只需使用float(line).

为了以防万一,最好去掉行首和行尾的所有空格。所以:

for line in infile:
    i = float(line.strip())
    # ... count
于 2013-06-05T18:43:34.777 回答
3

您正在使用一个额外的循环。此外,从文件中读取的数据以 str 形式出现,其中 "\n" 作为 endline char。使用 strip() 删除“\n”,然后将数据转换为浮点数。

结束代码应该是这样的:

counterPos = 0
counterNeg = 0
counterTot = 0
counterNeu = 0
with open('temp.txt', 'r') as infile:
        counterTot += 1
        for i in infile:            
                if float(i.strip()) > 0.3:
                    counterPos += 1
                elif float(i.strip()) < -0.3:
                    counterNeg += 1
                else:
                    counterNeu += 1
于 2013-06-05T18:56:28.020 回答
-1

当我发现自己做了很多测试时,我通常会按照以下方式做一些事情:

data='''\
  0.86149806
  1.8628227
 -0.1380086
 -1
  0.99927421
 -1.0007207
  0.99927421
  0.99926955
  -1.0007258'''

def f1(x):
    ''' >0.3 '''
    return x>0.3

def f2(x):
    ''' <-0.3 '''   
    return x<-.3

def f3(x):
    ''' not f1 and not f2 '''   
    return not f1(x) and not f2(x)

tests={f1: 0,
       f2: 0,
       f3: 0 }

for line in data.splitlines():
    for test in tests:
        if test(float(line.strip())): 
            tests[test]+=1

for f,v in sorted(tests.items()):
    print '{:3}{:20}:{}'.format(f.__name__, f.__doc__, v)

印刷:

f1  >0.3               :5
f2  <-0.3              :3
f3  not f1 and not f2  :1
于 2013-06-05T20:10:31.327 回答