尝试编写一个python程序,从文件中读取数字并计算平方和

时间:2014-04-12 02:22:05

标签: python

我正在尝试编写一个程序,从文件中读取数字,然后计算数字的平方和。该程序应该提示用户输入文件的名称并打印方块的总和。它提供了一个使用readlines()的提示,但这对我没什么帮助。我已经尝试了几个小时来提出一个正常工作的代码,但无法正常工作!我准备好把头发拉出来!!!这是我的代码:

我的档案代码:

def main():
    filename = input("Enter the name for the file: ")
    infile = open(filename, 'w')
    numList = input('Enter any numbers(seperated by a space): ')
    print(numList, file=infile)

main()

我的程序代码:

# function to convert list of strings to real numbers
def toNumbers(nums):
    for i in range(len(nums)):
        nums[i] = int(nums[i])

# function to square the numbers in a list
def numsquare(nums):
    for i in range(len(nums)):
    nums[i] = nums[i]**2

# function to add the numbers in the list
def sumList(nums):
    total = 0
    for i in nums:
        total = total + i
    return total

# program that pulls numbers from file and computes sum of the square of the numbers
def main():
fname = input("Please enter the name of the file to be opened: ")
nums = open(fname, 'r')

print("The numbers in this list are:")
print(nums)

# Convert strings in list to actual numbers
toNumbers(nums)
# Square the numbers in the list
numsquare(nums)
# Get the sum of the numbers in the list
sumList(nums)

total = sumList(nums)

print()
print("The sum of the numbers from this list is:", total)


main()

如果有人能告诉我我做错了什么,那将非常感激。这是我的第一本计算机科学课,欢迎任何建议。

4 个答案:

答案 0 :(得分:4)

在不知道文件结构的情况下,我至少可以告诉您,问题的一部分是您使用文件句柄作为“nums”变量,它不会为您提供内容。

为了从文件中提取数据,您需要在文件句柄上调用.read()或.readline()。

fname = input("Please enter the name of the file to be opened: ")
file = open(fname, 'r')

lines = file.readlines()

行现在包含一个列表,其中每个条目都是文件一行的内容

如果每行有一个数字,您应该能够将每个列表条目的内容强制转换为int以获取数字列表。

如果每行有多个数字,则需要在每个列表条目上使用split()来提取每个单独的数字。

答案 1 :(得分:0)

' readLines()'返回一个列表。然后你用a来导航列表。

lines = nums.readlines()

收到num返回的open(fname, 'r')是一个流而不是文本。因此,您必须在之后使用nums.readlines()。查看python的函数map,非常有用,可以帮助你。

答案 2 :(得分:0)

调试任何代码的第一件事是在不同的点打印出来,检查你是否得到了所需的输出。

nums = open(frame,'r'); print(nums)您会注意到打印nums 打印文件'frame'的内容。要获取文件的内容,您需要执行contents = nums.readlines()contents = nums.read()。前者将为您提供一个列表,其中每个条目(这是一个字符串)是文件的一行。第二个将为您提供转换为单个字符串的整个文本。

示例如下:
my_text_file:说f.txt

12 1 2 3 4 5 6

 8

21 

32

7
nums = open('f.txt','r')
f = nums.readlines()           #f = nums.read()
>>>['12 1 2 3 4 5 6\n', '\n', ' 8\n', '\n', '21 \n', '\n', '32\n', '\n', '7'] 

#The above line is the output for nums.readlines()

>>>'12 1 2 3 4 5 6\n\n 8\n\n21 \n\n32\n\n7'

#The above line is the output for nums.read()

现在您必须执行适当的步骤来转换字符串以分隔数字并将它们转换为int / float然后执行计算。

答案 3 :(得分:0)

这是一个有评论的工作程序。如果您有任何理解,请告诉我。

阅读评论(标有#)以更好地理解我添加的一些内容。

此外,如果您使用的是Python 3.x,请继续使用input()进行输入,但如果您使用的是Python 2.x,请使用raw_input()获取输入。

# function to convert list of strings to real numbers
def toNumbers(nums):
    for i in range(len(nums)):
        nums[i] = int(nums[i])

# function to square the numbers in a list
def numsquare(nums):
    for i in range(len(nums)):
        nums[i] = nums[i]**2

# function to add the numbers in the list
def sumList(nums):
    total = 0
    for i in nums:
        total = total + i
    return total

# program that pulls numbers from file and computes sum of the square of the numbers
def main():
    fname = input("Please enter the name of the file to be opened: ")
    nums = open(fname, 'r')
    strings = ""
    #create a string rather than a list with readlines
    #so we can remove extra spaces with the .split() method later
    for line in nums.readlines():
        strings += line

    #make sure to close nums
    nums.close()

    #remove spaces and store this result in the list nums_array
    nums_array = strings.split()

    print("The numbers in this list are:")
    print(nums_array)

    # Convert strings in list to actual numbers
    toNumbers(nums_array)
    # Square the numbers in the list
    numsquare(nums_array)
    # Get the sum of the numbers in the list
    sumList(nums_array)

    total = sumList(nums_array)

    print
    print("The sum of the numbers from this list is: " + str(total))

main()

>>> Please enter the name of the file to be opened: i.txt
    The numbers in this list are:
    ['1', '2', '3', '4', '5', '6', '7', '8']

    The sum of the numbers from this list is: 204

其中i.txt包含:

1 2 3 4
5 6 7 8
相关问题