如果行中的模式然后在具有模式python3的行下划线

时间:2018-03-12 08:19:13

标签: python python-3.x

我正在努力获得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('\033[1m' + 'pp')
          #print('\033[0m' + 'pp')

以下是我使用..

的课程顺序
   BOLD = '\033[1m'
   UNDERLINE = '\033[4m'

期望的输出:

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

1 个答案:

答案 0 :(得分:0)

  • Shell标记保持活动状态,直到您取消它,因此匹配的行 应以' \ 033 [0m'
  • 布尔值patt_success不是必需的,你可以按行处理
  • 您应该在“成功”字样前添加空格,否则它也会匹配“不成功”

工作版:

UNDERLINE = '\033[4m'
END = '\033[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)