如果模式在行中,则在具有模式 python3 的行下划线



我正在努力获得if pattern in line then underline the Entire line having pattern但作为一个新手学习者,我不知何故无法适应这个技巧。

以下是我要处理的文件。.

# cat mytest.txt
All records went successful
record1
record2
All records went unsuccessful
record3
record4
All records went successful
record5
record6

在我尝试的下面,但是当条件满足时,所有行都underlined

patt_success = False
with open("mytest.txt") as f:
  for line in f:
      if patt_success:
          if "successful" in line:
              patt_success = True
          else:
              patt_success = False
              pp = line.rstrip('n')
              print('33[1m' + 'pp')
          #print('33[0m' + 'pp')

以下是我正在使用的类顺序。

   BOLD = '33[1m'
   UNDERLINE = '33[4m'

期望输出:

# cat mytest.txt
All records went successful
----------------------------
record1
record2
All records went unsuccessful
record3
record4
All records went successful
---------------------------
record5
record6
  • 外壳标记将保持活动状态,直到您取消它,因此匹配的行应以"\033[0m"结尾
  • 布尔patt_success不是必需的,您可以每行处理它
  • 您应该在"成功"一词前面添加一个空格,否则它也将与"不成功"匹配

工作版本:

UNDERLINE = '33[4m'
END = '33[0m'
with open("mytest.txt") as f:
  for line in f:
      pp = line.rstrip('n')
      if " successful" in line:
          print(UNDERLINE + pp + END)
      else:
          print(pp)

最新更新