这就是我的全部:
def count_num(filename):
myfile=open(filename)
text=myfile.read
words=text.split()
for word in words:
答案 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
。