我试图从文件中读取然后找到所有数值的总和。我在第19行继续得到一个不受支持的类型错误,当我尝试打印列表时,我得到一个非常奇怪的输出。该文件在下面,我只需要读取数值。
文件
q
瓦特
ë
[R
吨
ý
û
我
0
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)
答案 0 :(得分:1)
使用regexp:
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())
答案 1 :(得分:0)
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)
假设您的输入文件onle每行都有一个简单的字符串。这会评估该行是否可以转换为float,然后将该float附加到列表中。
答案 2 :(得分:0)
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
答案 3 :(得分:0)
这几乎是 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更简单一些,并且在对它们求和之前不构建(可能很大的)数字列表。