如何打开包含数字的文本文件,并打印总和。必须使用for / while循环吗?

时间:2014-04-13 05:24:33

标签: python for-loop while-loop sum

标题说全部,我希望有一个脚本打开一个文本文件,找到数字,(数字形式不像"一个""两个"等)和打印/返回这些数字的总和。

这就是我的全部:

def count_num(filename):
    myfile=open(filename)
    text=myfile.read
    words=text.split()
    for word in words:

3 个答案:

答案 0 :(得分:0)

简单方法

def count_num(filename):
    myfile = open(filename)
    text = myfile.read() # Note: added parentheses
    words = text.split()
    sum_ = 0
    for word in words:
        # Check if can convert to int type safely
        sum_ += int(word) if word.isdigit() else 0

    return sum_

print(count_num(some_file))

或略好一点:

def count_num(filename):
    text = open(filename).read()
    numbers = map(int, filter(lambda x: x.isdigit(), text.split()))
    return sum(numbers)

print(count_num(some_file))

答案 1 :(得分:0)

def count_num(filename):
    nums = open(filename).read().split()
    sums = 0
    for k in nums:
        sums+=(int(k))
    return sums

在名为nums.txt的文件中包含以下数据:

1 3 5 3 2 5 3 4 2 42 12 43

代码如下运行

>>> count_num('nums.txt')
125

答案 2 :(得分:0)

假设文件只有数字而没有文本,那么您的解决方案就像执行:

一样简单
def count_num(filename):
    myfile=open(filename)
    text=myfile.read()
    words=text.split()
    n_data = [int(a) for a in words if a.isdigit()]
    return sum(n_data)

sum()是python中的内置类型,它返回一个可迭代的总和。

我们n_data = [int(a) for a in words if a.isdigit()]将字符串格式的所有数字转换为int