【问题标题】:Print out first word in each row from .txt file in python从python中的.txt文件中打印出每一行中的第一个单词
【发布时间】:2020-06-05 02:50:32
【问题描述】:

我正在开发一个程序,该程序从 .txt 文件中获取学生姓名和成绩并生成结果。文本文件有这种形式:

Darnell 96 54 94 98 76

Brody 50 65 65 65 70 

Anna 76 54 76 76 76

Conor 95 95 95 95 

我希望输出的第一行显示学生的姓名,如下所示:

Name of students in class:
Anna Brody Conor Darnell

我当前的代码是

   f = open(argv[1])
   while True:
      line = f.readline().strip()
      if line:
         print(line)

我知道我需要使用sorted() 函数。但是,当我尝试实现它时,我只是把代码弄得一团糟。

我知道那里有类似的问题。然而,对于 python 来说,有些是我的头。 任何一点点信息都会有所帮助。谢谢!

【问题讨论】:

  • "我想让输出的第一行显示学生的名字,像这样:" --> 第一行还是第一个单词??你为什么使用 while True??

标签: python python-3.x list sorting file-handling


【解决方案1】:

你可以试试这个。

我建议使用with open(...),因为您不需要显式使用close()

with open(argv[-1]) as f:
    names=[]
    for line in f:
        names.append(line.split()[0])

print(*sorted(names),sep=' ')
#Anna Brody Conor Darnell

按照@Jan 的建议,您可以使用列表理解来编写所有这些内容。

Does using list comprehension to read a file automagically call close() 下面是我按照这个链接写的。

print(*sorted([line.split()[0] for line in open('score.txt','r') if line.split()]),sep=' ') #This single code does what you wanted
#Anna Brody Conor Darnell

但我建议在下面使用这个答案。

with open(argv[-1],'r') as f:
    print(*sorted([line.split()[0] for line in f],sep=' ')

如果行之间有行间距,请使用此选项。

with open('score.txt','r') as f:
        names=[]
        for line in f:
                if line.strip():
                        names.append(line.split()[0])
print(*sorted(names),sep=' ')

【讨论】:

  • 您可能想要使用 listcomp。
猜你喜欢
  • 2013-10-09
  • 2022-11-26
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多