读取文件中的所有数字并在python中计算它们的总数

时间:2014-12-04 20:41:33

标签: python

我正在尝试计算给定文件中的所有数字。除非数字之间有单词,否则它有效。 例如:

1
2
car
3
4

这是我的代码:

def main():
count=0
with open("numbers.txt", "r") as f:
    try:
        line = f.readline()
        while line != '':
            print(line.strip())
            count += int(line)
            line = f.readline()

    except Exception as err:
        print(err)

    print(count)

main()

我正在考虑继续,但它只适用于for或while。那有什么办法吗?

4 个答案:

答案 0 :(得分:1)

您可以使用isdigit来检查号码:

while line != '':
        print(line.strip())
        if line.strip().isdigit():
            count += int(line.strip())
        line = f.readline()

这是Pythonic实现这一目标的方式 如果你想总和所有数字:

f = open('file')
total_count = sum(int(x) for x in f if x.strip().isdigit())

如果你想计算它们中有多少是数字:

f = open('file')
total_digit = len(x for x in f if x.strip().isdigit())

答案 1 :(得分:1)

您应该在循环中移动tryexcept块。然后当你点击一个非数字的行时,你只需跳过它然后继续下一行。

与该错误无关,您还可以通过在for循环中直接迭代文件来简化代码,而不是在readline循环中重复调用while:< / p>

with open("numbers.txt", "r") as f:
    for line in f:          # simpler loop
        print(line.strip())
        try:                # move this inside the loop
            count += int(line)
        except Exception as err: # you may only want to catch ValueErrors here
            print(err)

    print(count)

答案 2 :(得分:0)

您可以使用isdigit方法检查该行是否仅包含数字:

def main():
    count=0
    with open("numbers.txt", "r") as f:
        count = sum(int(line) for line in f if line.strip().isdigit())
        print(count)

if __name__ == '__main__':
    main()

答案 3 :(得分:0)

您可以尝试使用正则表达式:

import re

total = 0

with open("numbers.txt", "r") as f:
    line = f.readline()
    while line != '':
        total += sum([int(x) for x in re.findall('(\\d+)', line)])
        line = f.readline()
print total