只需要从文件中读取数值,然后对它们求和

Need to read only numeric values from a file and then sum them

我正在尝试从文件中读取,然后找到所有数值的总和。我在第 19 行不断收到不受支持的类型错误,当我尝试打印列表时,我得到了一个非常奇怪的输出。该文件在下面,我只需要读取数值。

文件

q

w

e

r

t

y

u

i

o

p

1

2

3

4

5

6

7

8

9

0

[

]

,

.

/

0.9

9.8

8.7

7.6

6.5

5.4

4.3

3.2

2.1

1.0

def sumOfInt():

with open("sample.txt", "r") as infile:
    list = [map(float, line.split()) for line in infile]
    sumInt = sum(list)

print("The sum of the list isi:", sumInt)

使用正则表达式:

import re

with open("sample.txt", "r") as infile:
    total = sum(map(float, re.findall("\d+.\d+|\d+", inifile.read())))

如果您需要所有数值的列表:

with open("sample.txt", "r") as infile:    
    values = re.findall("\d+.\d+|\d+", inifile.read())
def sumOfInt():

  with open("sample.txt", "r") as infile:
      floatlist = []
      for line in infile:
          try:
              floatlist.append(float(line))
          except:
              pass
      sumInt = sum(floatlist)

      print("The sum of the list isi:", sumInt)

假设您的输入文件每行只有一个简单的字符串。这会评估该行是否可以转换为浮点数,然后将该浮点数附加到列表中。

我的第一个答案中缺少整数:

with open('data') as f:
    text = f.read()
    print(sum([ float(x) for x in re.findall(r'\d+.\d+|\d+|^.\d+', text)]))


# output:
94.5

这是几乎 R Nar 的回答:

def sumOfInt():
    with open("sample.txt", "r") as infile:
        total = 0
        for line in infile:
            try:
                total += float(line)
            except ValueError:
                pass

print("The sum of the list is:", total)

...不同之处在于 try/except 更简单一些,它不会在对数字求和之前构建(可能很大的)数字列表。