вывод строки после ключевого слова python

#python #regex #string #file

#python #регулярное выражение #строка #файл

Вопрос:

Мне удалось извлечь следующую строку из текстового файла

 05/19/2014, 15:24:14.455> LVL:2 RC:   0          SERVER :server main: TERA_MGMT_SYS_SESS_EVENT_RESET with disconnect cause (0x105)
  

как 105 теперь извлечь из него?

 #!/usr/bin/env python
import sys, re, os

lineContains = re.compile(r'(?=.*disconnect cause)')
lineContainsCode = re.compile(r'causes*(.*?(d ))')
filename = open ("pcoip_server_2014_05_19_00000560.txt", 'r')

for line in filename:
    if lineContains.match(line):
        print 'The file has: '
        print line
        code = lineContainsCode.search(line).group(1)
        print 'The code is:', code
        if code == 001:
            print 'PCoIP session terminated due to lost network.'
        elif code == 100:
            print 'PCoIP connection not established due to failure of PCoIP server initialization. This should not occur. Please contact Teradici support.'
        elif code == 101:
            print 'PCoIP connection not established due to failure of PCoIP server initialization. This should not occur in normal operation. Note: If the Welcome Screen is enable in the View Administrator a ConnectionTicketTimeout will trigger a disconnect after 15 min with this code'
        elif code == 102:
            print 'PCoIP session terminated due to VMware View Connection Server (broker) maximum session duration (Connection Server setting) exceeded.'
        elif code == 103:
            print 'PCoIP session terminated due to the VDI user selecting Logoff or Restart from Windows in the VDI session'
        elif code == 104:
            print 'PCoIP session terminated due to admin manually disconnected the session from the Administrative Web Interface.'
        elif code == 105:
            print 'PCoIP session terminated due to login from an alternate location OR Pre-connection warmup initialization of PCoIP Server. This is not for actual connection. If the size of the log is under 15 Kbytes, this is a pre-connection warmup startup/shutdown sequence.'
        elif code == 200:
            print 'PCoIP session terminated due to the user right-clicking the host driver icon in the tray and then selecting Menu > Disconnect. Applicable only to clients connecting to a hard host and not VDI.'
        elif code == 201:
            print 'PCoIP connection not established due to incompatible host driver version (not used for VDI).'
        elif code == 300:
            print 'PCoIP session terminated due to the user closing the View Client window or due to the user ending the View application task inside the Windows Task Manager'
        elif code == 301:
            print 'PCoIP session terminated due to the user clicking the zero client's Disconnect button. Not applicable for soft clients.'
        elif code == 302:
            print 'PCoIP session terminated due to the user clicking the Disconnect button in the client Administrative Web Interface. Not applicable for soft clients.'
        elif code == 303:
            print 'The VMware View Connection Server (broker) requested the session to end.'
        elif code == 304:
            print 'PCoIP session terminated due to Power Sleep disconnect (not used for VDI).'
        elif code == 305:
            print 'PCoIP session terminated due to user pulling out the smart card used for user authentication.'
        elif code == 306:
            print 'PCoIP session terminated due to user taking action specified by OneSign to be a disconnect command (for example, double tapping the card).'
        elif code == 400:
            print 'Zero client and View 4.5 and earlier: PCoIP session terminated due to network issues on TCP/SSL connection (keepalive ping timeout).'
        elif code == 401:
            print 'PCoIP connection not established due to networking issues or failure to open drivers, such as video, audio, or USB.'
        elif code == 402:
            print 'PCoIP connection not established due to networking issues.'
        elif code == 403:
            print 'PCoIP session terminated due to various reasons. For example, network lost or client/server crash.'
        elif code == 404:
            print 'PCoIP connection not established due to inability to use the VMware video driver on the server.'
        elif code == 405:
            print 'PCoIP connection not established due to client and server not having a common encryption method enabled.'
        elif code == 406:
            print 'Zero Client and View 4.5 and earlier: PCoIP session terminated due to network issues on TCP/SSL connection. Zero client and View 4.6 (and later). This is normal operation since the TCP/SSL connection is terminated right after session negotiation.'
        elif code == 407:
            print 'PCoIP connection not established due to the View Security Server detecting that AES encryption is disabled on either the client and/or server.'
        else:
            print 'code not found in KB.'

filename.close()
  

выдает мне файл с ошибкой «pcoip_disconnect_codes.py «, строка 20 код elif == 102: ^ Ошибка отступа: unindent не соответствует ни одному внешнему уровню отступа

Ответ №1:

Вы можете попробовать приведенное ниже регулярное выражение, чтобы получить числа внутри () paranthesis. Приведенное ниже регулярное выражение содержит строку cause , потому что было бы полезно правильно сопоставить точную строку, а также числа внутри () .

 cause (.*?(d ))
  

ДЕМОНСТРАЦИЯ

введите описание изображения здесь

Ваш код будет,

 lineContainsCode = re.compile(r'cause (.*?(d ))')
  

Комментарии:

1. ‘code = lineContainsCode.search(line).group(1) распечатать код, если code == ‘150’: { print (‘см. кб’) }’ пытаюсь использовать if, но, похоже, не работает и выдает сообщение об ошибке: File «pcoip_disconnect_codes.py «, строка 17 print (‘см. kb’) ^ Ошибка синтаксиса: недопустимый синтаксис @Rakesh KR

Ответ №2:

Для подхода без регулярных выражений:

 code = line.split("(")[-1].split(")")[0].split("x")[-1]
# more readable:
# code = line.split("(")[-1]
#            .split(")")[0]
#            .split("x")[-1]
  

Это разделит строку на все буквальные открытые скобки и проиндексирует -1 (т. Е. захватит последний). Затем разделите это на все литералы, закрывающие скобки, и индексируйте 0 (т. Е. захватите ПЕРВЫЙ), затем разделите на все литералы "x" и индексируйте -1 (т. Е. захватите последний)

 KEY: ---- items not selected
          items selected
       |  split point (NOT SELECTED)

1.
05/19/2014, 15:24:14.455> LVL:2 RC:   0          SERVER :server main: TERA_MGMT_SYS_SESS_EVENT_RESET with disconnect cause (0x105)
---------------------------------------------------------------------------------------------------------------------------|      

2.
0x105)
     |--

3.
0x105
-|   
  

В результате 105

РЕДАКТИРОВАТЬ ПРИМЕР ХЭШ-КАРТЫ:

 code = lineContainsCode.search(line).group(1)
hashmap = {"001":'PCoIP session terminated due to lost network.',
           "100":'PCoIP connection not established due to failure of PCoIP server initialization. This should not occur. Please contact Teradici support.',           
            ...
           "407":'PCoIP connection not established due to the View Security Server detecting that AES encryption is disabled on either the client and/or server.'}
error_msg = hashmap.get(code,'code not found in KB.')
print(error_msg)
  

Комментарии:

1. я использовал это, и оно распечатало 0x105 , есть ли какой-нибудь способ просто вытащить 105. Я и в самом деле плох в этом, и не могли бы вы разбить его или объяснить, пожалуйста @Adam Smith

2. ‘code = lineContainsCode.search(line).group(1) распечатать код, если code == ‘150’: { print (‘см. кб’) }’ пытаюсь использовать if, но, похоже, не работает и выдает сообщение об ошибке: File «pcoip_disconnect_codes.py «, строка 17 print (‘см. kb’) ^ Ошибка синтаксиса: недопустимый синтаксис

3. @user3731311 как долго вы пишете на python? Не используйте фигурные скобки для обозначения блоков кода….

4. не слишком долго, я тоже пытался удалить {} . после получения кода я попробовал ‘if code == 150: print ‘использовать это» похоже, не работает @Adam Smith спасибо за вашу помощь

5. @user3731311 трудно сказать, не видя вашего полного кода 🙂