如何在Python中找到.txt文件中某一列的总和?

时间:2019-05-07 18:17:48

标签: python python-3.x indexing

我有一个.txt文件,其中包含3行和3列数据,如下所示:

public class DateMinimumAgeAttribute : ValidationAttribute
{
    public DateMinimumAgeAttribute(int minimumAge)
    {
        MinimumAge = minimumAge;
        ErrorMessage = "{0} must be someone at least {1} years of age";
    }

    public override bool IsValid(object value)
    {
        DateTime date;
        if ((value != null && DateTime.TryParse(value.ToString(), out date)))
        {
            return date.AddYears(MinimumAge) < DateTime.Now;
        }

        return false;
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessageString, name, MinimumAge);
    }

    public int MinimumAge { get; }
}


[DateMinimumAge(18, ErrorMessage="{0} must be someone at least {1} years of age")]
[DisplayName("Date of Birth")]
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> Date_of_Birth { get; set; }

我正在寻找一个允许用户输入1,2或3的数字并获取指定列之和的功能

我收到的错误如下:

    1.5    3.1425    blank
    10       12       14
    8.2     blank     9.5

我只是在练习索引编制,在尝试选择要分析的特定列或行时遇到麻烦。我有以下代码,但遇到与索引超出范围或浮点对象不可迭代有关的错误

 Traceback (most recent call last):
   File "<pyshell#41>", line 1, in <module>
     summarizer(2)
   File "/Users/"practice.py", line 
   403, in summarizer
     print(sum(float(col2)))
   ValueError: could not convert string to float: '.'

如果用户输入了summary(3),我希望输出为23.5,因为14 + 9.5 + 0 = 23.5

3 个答案:

答案 0 :(得分:1)

我在脚本上加了注释。您可以创建三个列列表以收集相应列中的每个值。然后总结一下。

def summarizer(searchNum):
    infile = open('nums.txt','r')
    fileContents = infile.readlines()
    infile.close

    col1, col2, col3 = [], [], []   #initialize the columns

    for numbers in fileContents:
        numVals = numbers.replace('\n','').split('\t')    #also remove newline at the end (\n)
        col1.append(float(numVals[0]) if numVals[0] else 0)   #convert to float if not blank else 0 then add to col1
        col2.append(float(numVals[1]) if numVals[1] else 0)
        col3.append(float(numVals[2]) if numVals[2] else 0)

    if searchNum == 1:
        print(sum(col1))

    elif searchNum == 2:
        print(sum(col2))

    else:
        print(sum(col3))    #print the sum of col3

    return

结果:

summarizer(3)
23.5

答案 1 :(得分:0)

您需要确保文本文件的制表符格式正确。然后,您需要将每行追加到列表中,并用制表符分割每个值。

然后,您需要除去“空白”和“ \ n”或其他任何非数字。 然后总结一下。

这就是我要做的

infile = open('nums.txt','r')
fileContents = infile.readlines()
infile.close

newList = []   # List of lists. Each list is a column
for line in fileContents:
    newList.append(line.split('\t'))

# - Blank must be 0. Let's get rid of \n as well
for i in range(len(newList)):
    for j in range(len(newList[i])):
        if '\n' in newList[i][j]:
            newList[i][j] = newList[i][j].replace('\n', '')
        try:
            newList[i][j] = float(newList[i][j])   # get rid of string entries
        except ValueError:
            newList[i][j] = 0

sum = 0
if searchNum == 1:
    for i in range(len(newList)):
        sum += newList[i][0]
if searchNum == 2:
    for i in range(len(newList)):
        sum += newList[i][1]
if searchNum == 3:
    for i in range(len(newList)):
        sum += newList[i][2]
print(sum)

答案 2 :(得分:0)

说明“无法将字符串转换为浮点数:'。” ”错误:

col2变量具有字符串“ blank”(这不是整数)。  当您将float应用于不是整数的字符串(在我们的示例中是float(col2))时,它将引发您提到的错误。

您的代码的实际作用:

1。它将创建一个n * n 2d数组,并将文本文件中的所有元素放入2d数组。

2。您将每列中的最后一个元素分配给变量col1,col2,col3

3。您对每一列的最后一个元素应用求和运算

您正在尝试做什么:

1。创建一个n * n 2d数组,并将文本文件中的所有元素放入2d数组。

2。在每个列元素上应用求和运算并显示结果:

因此,您的代码实际上并未执行您想做的事情。 我已经写了下面的代码,实际上可以做到

解决方案代码

def summarizer(searchNum):
infile = open('nums.txt','r')
fileContents = infile.readlines()
infile.close

newList = []


for numbers in fileContents:

    # - replace the "blank" string and  with 0  and makes every instance 
    #- float  type  
    numbers =numbers.replace("blank","0").replace('\n','').split('\t')

   # - creates the 2d array of the items from you text file
   for i in range(1,len(numbers)+1):
      newList[i].extend(float(numbers[i-1])) 

   # - prints the sum based on column index u wanted 
print(sum(newList(searchNum)))   

通过使用csv库,您可以更轻松地完成此操作          https://docs.python.org/2/library/csv.html