Python - 将文件内容从字符串转换为int

时间:2015-09-09 11:38:19

标签: python

我有一个程序可以将您在程序中获得的分数保存在一个单独的文件中,但是,该文件会将分数保存为:

  

2 4 6 8 9 8

我的问题是我无法将这些转换为整数,因此我可以将它们全部加在一起。

就我而言:

scores = open("scores.txt", "r")

之后我尝试过的所有事情都会出现不同的错误。

任何人都知道该怎么做?

5 个答案:

答案 0 :(得分:1)

  

这是我走了多远...“得分=开(”scores.txt“,”r“)”之后我所尝试的一切都以不同的错误结束。任何人都知道该怎么做?

我建议用分隔符拆分字符串。

你可以通过直线穿过文件来做到这一点。

for line in scores:
  splitted_line = line.split(' ')
  for values in splitted_line:
    value_as_int = int(values)
    # ... do something with value now

我认为扫描和处理大数据的另一个建议是笨拙的。 several functions会为您导入数据。

我可以为自己推荐 genfromtext function 。您可以在那里定义填充值,分隔符等等。

答案 1 :(得分:1)

按如下方式进行:

with open("scores.txt", "r") as f:
    score = f.read() # Read all file in case values are not on a single line
    score_ints = [ int(x) for x in score.split() ] # Convert strings to ints
    print sum(score_ints) # sum all elements of the list

37

答案 2 :(得分:1)

有两种方法可以做到这一点:

第一个假设另一个程序输出具有单空格分隔符的一致正整数。您可以使用以下代码:

with open('scores.txt', 'r') as f:
    lines = f.read(); 
    q = lines.split(' ')    
    a = sum(map(int, q))

print a

第二种解决方案是使用正则表达式:

import re
intpattern = '[+-]?\d+'

with open('scores.txt', 'r')as f:
    lines = f.read(); 
    m = re.findall(intpattern, lines)
    a = sum(map(int, m))

print a

答案 3 :(得分:0)

尝试:

with open("scores.txt", "r") as f:
    for l in f;
        print(sum([int(a) for a in l.split()]))

答案 4 :(得分:-1)

  

我无法将这些转换为整数,因此我可以将它们全部加到一个总和中(在这种情况下为2 + 4 + 6 + 8 + 9 + 8 = 37)

您可以拆分一条线,将每个字符串转换为整数,然后对所有数字求和。您也可以将这些总和存储在列表中并计算平均值。

试试这个:

sums = []
with open("scores.txt", "r") as f:
  for line in f:
    numbers = line.split() # 2 4 6 8 9 8
    s = 0
    for number in numbers:
        try:
            s += int(number)
        except:
            print 'can not cast to integer'
    sums.append(s)
  avg = sum(sums) / float(len(sums))