n 从文本文件中读取数据并在新行中输出每个名称和数字对 (Python)

问题描述 投票:0回答:2

我一直坚持这个任务,真的需要一些帮助。

我在文本文件中有一个数据:

John 46.5 Sam 62 Steve 45.5 Nigel 67.1 Karen 55
Henry 55 Alex 42 Graham 82 Hannah 56 Nicola 66
Ruth 81 Carl 90 Ben 66.8 

并且需要编写一个程序,可以从文本文件中读取数据并在新行中输出每个名称和数字对,如下所示:

>>>
John : 46.5
Sam : 62
Steve : 45.5
Nigel : 67.1
Karen : 55
Henry : 55
Alex : 42
Graham : 82
Hannah : 56
Nicola : 66
Ruth : 81
Carl : 90
Ben : 66.8
AVERAGE: 62.684615384615384
>>> 

我可以从文件中输出文本并分离它包含的元素,但是我无法设置条件中指定的正确输出。


f = open("grades.txt", "r")
d = f.read()
f.close()
print(d)
print()

d = d.splitlines()
print(d)
for line in d:
    print(line)
    line = line.split()
    print (line)
    
print()

如果你能给我一些建议,帮我解决这个任务,我将不胜感激

提前致谢

python text-files
2个回答
0
投票

您可以按行阅读文本,然后将其拆分为单词数组。试试这个:

values = []
with open('test.txt') as f:
  lines = f.readlines()
  for i in lines:
    data = i.strip().split(' ')
    counter = 0
    for j in data:
      if counter % 2 == 0:
        string = ''
        string += j + ' : '
      else:
        if round(float(j)) == int(float(j)):
          values.append(int(float(j)))
          string += j
        else:
          values.append(float(j))
          string += j
        print(string)
      counter += 1
  print('AVERAGE:',sum(values)/len(values))

0
投票
  1. 我们可以通过
    with
    语句
    open
    的组合打开文件并读取其内容。请注意,我们不需要它的
    "r"
    参数,因为如果没有传递参数,它默认为
    "r"
  2. 然后我们可以使用
    str.split
    拆分文件的读取内容,当没有提供参数时默认拆分所有空格。
  3. 然后我们在遍历列表之前将累积和初始化为零。
  4. 然后我们以步长 2 遍历您之前创建的列表,因此
    i
    始终是偶数。这意味着
    split_text[i]
    总是一个名字,而
    split_text[i+1]
    总是一个数字。
  5. 在你的循环中,我们可以使用 slicing 将它们解压成两个变量。
  6. 仍在您的循环中,我们使用
    print
    fstring 输出名称和值。
  7. 最后,在您的循环中,我们增加累积和。但是,由于我们不能通过字符串递增数值,因此我们必须先将其转换为数值。由于上面给出的一些值是 floats,我们必须使用
    float
    而不是
    int
    ,因为如果我们使用后者,它会引发
    ValueError
    .
  8. 一旦我们离开你的循环,我们就会计算值的数量,这是文件拆分内容的
    len
    的一半。
  9. 最后,我们通过将总和除以值的数量并打印它来计算您的平均值。
    # Open the file and read the contents
    with open("grades.txt") as file:
        # split the contents on whitespace
        split_text = file.read().split()

    # Initialise the cumulative sum to zero
    cumulative_sum = 0

    # Iterate through the list with step size 2
    for i in range(0, len(split_text), 2):
        # Use slicing and multiple assignment to get the name and the value
        name, value = split_text[i:i+2]

        # Output the name and the value
        print(f'{name} : {value}')

        # Increase the cumulative sum
        cumulative_sum += float(value)

    # Output the final average
    n = len(split_text)/2
    print('AVERAGE:', cumulative_sum/n)

输出:

John : 46.5
Sam : 62
Steve : 45.5
Nigel : 67.1
Karen : 55
Henry : 55
Alex : 42
Graham : 82
Hannah : 56
Nicola : 66
Ruth : 81
Carl : 90
Ben : 66.8
AVERAGE: 62.684615384615384
© www.soinside.com 2019 - 2024. All rights reserved.