Python计数输入文件中的数字

时间:2017-12-23 16:45:53

标签: python file count

我想编写一个Python 3脚本来读入输入文件,如下所示:

8 13 67 43 47
9 19 5 3 69
93 21 25 53 20

然后计算文件中有多少个数字并找到最大值。我写了以下脚本:

file = open ("input.dat","r")
count = 0
for line in file :
   parts = line.split()
   count +=1
   print (count)

但它只计算行数。我如何计算数字?在文件?

5 个答案:

答案 0 :(得分:0)

你说你不想使用列表。但是,split()方法作用于字符串并将其转换为列表。我将我的答案集中在你特别提到的两个要求上。如果还有其他要求,请在下面的评论中提及。

计算数字

为此,您可以简单地读取每一行,使用拆分将其分解为数字列表,然后将该字符串的长度添加到运行总计中。

以下是相同的代码:

file = open ("input.dat","r")
total_numbers = 0
for line in file :
   parts = line.split()
   total_numbers += len(parts)
print (total_numbers)

查找最大数量

至于找到最大数量,对于每一行,您可以使用内置max函数找到最大数量,并从每行的最大数量中选择最大数量。

这就是它的实现方式。

file = open ("input.dat","r")
total_numbers = 0
# Storing the most minimum number possible inside max_num
# '-inf' is a special string which implies tending to negative infinity
max_num = float('-inf')
for line in file :
   parts = line.split()
   # split() stores the numbers as a string inside the list
   # map() converts the list of strings into a list of integers
   parts = map(int, parts)
   max_num_in_line = max(parts)
   # If the maximum number in the line being read is more than max_num, replace max_num by that number
   if max_num_in_line > max_num:
      max_num = max_num_in_line
print (max_num)

我希望这会有所帮助。如果您需要进一步澄清,请告诉我。

答案 1 :(得分:0)

您可以使用列表轻松完成所需的一切:

with open ("input.dat","r") as file:
    data = file.read()

#Extract all integers in the file into 1 list
list_of_integers = [int(i) for i in x.replace('\n',' ').split()] 

#Now you can whatever you please
count(list_of_integers)
max(list_of_integers)
sum(list_of_integers)
...

答案 2 :(得分:0)

如果您不想在解决方案中使用list,可以尝试计算所有数字的最大数量和数量

file = open ("input.dat","r")
count = 0
max = 0
for line in file :
   #Reading file will result in list of numbers like ['1', '2', '3'], so you have to map them to int
   parts = list(map(int, line.split()))
   #Count of all numbers in a line
   count = count + len(parts)
   #Max number in a lint
   max_iter = max(parts)
   #Update max if previous max was smaller
   if max_iter > max:
      max = max_iter
print ("Total Numbers: {}, Maximum Number: {}".format(count,max))

答案 3 :(得分:0)

import re

digit_count=0
number_count = 0
numbers = []
count=0

with open ("letters_and_numbers.txt") as f:
  for line in f.readlines():
    sub_strs = line.rstrip().split("-")
    for i in range(0, len(sub_strs)):
      file_words = re.split(r"[a-zA-Z\W]",sub_strs[i])
      for word in file_words:
        if word.isdigit():
          digit_count += len(word)
          number_count += 1
          if i >=1 and sub_strs[i].startswith(word):
            count-=int(word)
            digit_count+=1
            numbers.append("-")
            numbers.append(word)
          else:
            count+=int(word)
            numbers.append(word)

print "digits:",digit_count
print "amount of numbers:",number_count
print "numbers:",numbers
print "total:",count

即使文件看起来像这样,此代码也会计算文件中的数字:

gfwgf8943758834y34ty3yttubf37t73

答案 4 :(得分:0)

file = open ("input.dat","r")
sum = 0
for line in file :
   parts = line.split()
   sum+=len(parts)
   # Print the total number in a line
   print (sum)
   parts = map(int, parts)
   max_in_line = max(parts)
   if(max<max_in_line)
       max = max_in_line
print(sum)
print(max)