如何在一行中的特定单词上方打印行?

2024-09-21 07:53:27 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上我有一个文本文件,如下所示:

- Brandon = 1
- Mark = 70
- Charlie = 2
- Mark = 65
- Jon = 3
- Mark = 73
- May = 4
- Mark = 88
- Nathan = 5
- Mark = 95
- etc..

现在我需要一个程序来读取文本文件的所有行(我知道怎么做),并检查标记的值,如果它高于70,它将打印标记和它上面的行(这是学生姓名的行)。有没有人知道这是怎么做到的,因为我一点线索都没有。谢谢你的帮助!在

谨致问候, 乔


Tags: 标记程序etc学生maymark姓名文本文件
2条回答

这里有一种方法可以解决这个问题,尽管我不打算解释它是如何工作的。您将需要研究regexlist comprehensionsenumerate内置方法等。在

import re

with open('myfile.txt', 'r') as f:
    lines = f.readlines()
    lines = [l.strip() for l in lines] # list comprehension
    for index, line in enumerate(lines):
        mark = re.search(r'\d+',line) # regex
        if int(mark.group()) > 70:
            print ('Mark: ', mark.group())
            print ('Line above:', lines[index-1])

注意:您需要删除文本文件中包含“-etc…”的最后一行代码才能正常工作。另外,文本文件中的每一行都必须有一个标记(分数)。也没有空行:) 如果您更改了txt文件,并且第一行的标记是>;70,那么“上面一行”实际上是文件的最后一行-至少在本代码中是这样。在

看看这里,看看你是否能理解这段代码在做什么。评论很好。在

#opening a file
path_to_file = '/usr/home/file.txt'

#reading file
#saving lines to a list
with open(path_to_file, "r") as f:
    l1.readllines(f)

#produced list
l1 = ['- Brandon = 1', '- Mark = 70', '- Charlie = 2', '- Mark = 65', '- Jon = 3',
      '- Mark = 73', '- May = 4', '- Mark = 88', '- Nathan = 5', '- Mark = 95']


#counter to check and get the previous line  
counter = 0

#iterate over list    
for i in l1:

    #define what score is, and save it as int
    score = int(i.split("=")[1])

    #conditional check
    if score > 70:
        #if condition is true, then print previous line
        print l1[counter-1]

    #autoincrement
    counter += 1

产量:

^{pr2}$

如果将print l1[counter-1]更改为print l1[counter]print i,您将得到以下输出:

- Mark = 73
- Mark = 88
- Mark = 95

如@taesu所说,你应该搜索如下句子:

  • 如何用python打开文件
  • 如何在python中读取文件
  • 如何在python中循环
  • 如何用python打印

因为这是您的任务所需的工作流。在

  • 打开文件
  • 阅读行
  • 对于每一行,检查条件是否为真
  • 如果条件是真的,那么
  • 做点什么

很简单。在

相关问题 更多 >

    热门问题