Как получить конкретный текст из строки изменяющейся длины? - PullRequest
0 голосов
/ 05 февраля 2019

У меня есть строка, содержащая информацию, которую я хотел бы извлечь.Моя проблема в том, что длина строки может меняться в зависимости от версии продукта, имени пользователя, пароля и т. Д. Поэтому я не могу просто сказать переменную [155: 185].Я думаю, что это может быть решением для регулярных выражений, но я никогда не работал с регулярным выражением и не уверен.

Я пытался использовать переменную [155: 185], но это не работает из-за отсутствия определенной длины строки.

_____ Это строка, которую я извлекаю из _____

[('loginTapped () - успешный вход в систему. Id: fakeemail@gmail.com - Password123',), ('loginTapped () - кнопка входа - версия: 1.03.29 (29)',), ('logFoundBleNames () - найдено bleNames:, VR0796a3',), ('viewDidLoad () - viewDidLoad',), ('waitTimerSerialNumEvent (timer :) - найдено устройство XY: VR0796a3 и серийный номер: macAddress: 0025ca0796a3 ',), (' wifiScanTimerEvent (timer :) - запрошен список Wi-Fi. Имя: VR0796a3 ',), ('ridgeTapped () - Seag_to_enter_pin_sid', ('viewDidLoad () - viewDidLoad',), ('applianceTapped () - segue_to_wifi_select_sid',), ('viewDidLoad () - viewDidLoad',), ('подготовить (для: отправителя :) - segue_to_prod_wifi_setot_s с помощью Iid)), ('viewDidLoad () - Получил действительный mac: 0025ca0796a3',), ('viewDidLoad.) - Вызывается с: mac: 0025ca0796a3 apiKey: 757d1040 DevicePin: 1234 ',), (' setDevicePrivilegeCloud (macAddress: userApiKey: devicePin: privilegeCompletionHandler :) - \ nDevice Apikey: c8b428e2 \ pss (p), nss)- Введите setPassphrase с appliance.apParamOut.count: 38 - psswd len: 9 ',), (' onRecordButton - Вызов updateApplianceRecord () после облачного вызова ',), (' updateApplianceRecord () - обновление записи устройства: name: Optional ("XY0796a3 ") mac: 0025ca0796a3 serial: appl name: Необязательно (" Freezer ") modelID: 6 ',), (' setupChangeNotification () - Настройка завершена (уведомление).Возвращаясь к экрану выбора продукта сейчас. ',), (' SetupChangeNotification () - вызов updateApplianceRecord () в вызове уведомления ',)]

import _sqlite3
# SQL to readable text

#add a time stamp!!
from Functions import create_connection

global Error
Error = False
try:
    UserFile = open("UserFriend.txt", "w")

except:
    UserFile = open("UserFriend.txt", "w+")

filename = "perfect_viking_connect.db"
perfect = "perfect_viking_connect.db"
#type1 = "Crash"
#type2 = "Connection Issue"

#cause1 = "Possible too far away"
#cause2 = "Poor connection with router with eiter phone or appliance"

def Friendly_Output(line):
    # Begin Searching
    ####################################################################################################
        #Login
        #######################################################
    if Error == False and "Login in success" in line:
        UserFile.write("User Information" + line)
    if Error == True and "Login in Success" in line:
        UserFile.write("There was a Login Error")
        # Version
        ########################################################
    if Error == False and "Login Button" in line:  # and if next line doesn't load then and Error has occured
        UserFile.write("\nUser is on Version: " + line[42:49])
    #else:
        #UserFile.write("\nAn error has occurred on login possible errors are")  # + type1,type2,type3,type4)
        # Found Bluetooth
        ########################################################
    if Error == False and "Found bleNames" in line:  # and if next line doesn't load then and Error has occured
        UserFile.write("\nSystem has found the Bluetooth name: " + line[41:49] +"\n")
    #else:
        #UserFile.write("\nAn error has occurred while searching for Appliances Bluetooth")

        # Request Wifi List
        ########################################################
    if Error == False and "Found VR" in line:  # and if next line doesn't load then and Error has occured
        UserFile.write("\n______Wifi information______\nVR Appliance: " + line[56:64] + "\n" + "Serial:\n" + "macAddress: " + line[90:102])
    #else:
        #UserFile.write("\nAn error has occurred receiving appliance information")  # + type1,type2,type3,type4)

        # Nic Board wifi request
        ########################################################
    if Error == False and "waitTimerSerialNumEvent" in line:  # and if next line doesn't load then and Error has occured
        UserFile.write("\n\nNIC is requesting wifi list")
    #else:
        #pass
        # Enter Pin Screen
        ########################################################
    if Error == False and "enter_pin_sid" in line:  # and if next line doesn't load then and Error has occured
        UserFile.write("\nUser is passed to enter pin screen")
    #else:
        #UserFile.write("\nAn error has occurred transferring to pin screen")  # + type1,type2,type3,type4)")
        # Wifi selection screen
        ########################################################
    if Error == False and "wifi_select_sid" in line: # and if next line doesn't load then and Error has occured
        UserFile.write(("\nUser is selecting wifi connection from list"))
    #else:
        #UserFile.write(("\nThere was an error")) # + type1, type2, type3
        # Wifi Setup Screen
        ########################################################
    if Error == False and "wifi_setup" in line: # and if next line doesn't load then and Error has occured
        UserFile.write("\nUser is on wifi credentials page")
    #else:
        #UserFile.write("\nAn error has occurred while searching for appliances\n")  # + type1,type2,type3,type4)

        # User has pressed enter
        ########################################################
    if Error == False and " - wifi: " in line:  # and if next line doesn't load then and Error has occured
        UserFile.write("\nUser has entered credentials and pressed enter")
    #else:
        #UserFile.write("\nAn error has occurred while starting the cloud setup process\n")  # + type1,type2,type3,type4)

        # Adding pass/fail
        ########################################################
    if Error == False and "addWifiNameTo" in line:
        UserFile.write("\nUser has successfully added their connection")
    #else:
        #UserFile.write("\nThe wifi addition process has failed")

    '''     # Pinging cloud to add new information
        ########################################################
    if Error == False and "addWifiNameTo" in line:
        UserFile.write("\nUser has successfully added their connection")
    #else:
        #UserFile.write("\nThe wifi addition process has failed")'''
        ########################################################


        #Beginning Cloud talk
        ##########################################################################
    if Error == False and "Called with: mac:" in line:
        UserFile.write("\n\n____Cloud Talk has Begun____\nMac address: " + line[107:119] + "\nApikey: " + line[128:136] + "\nDevice Pin: " + line[148:152])
    if Error == True and "Called with: mac:"  in line:
        print("Cloud Talk Failed")
        #Device Apikey
        ########################################################
    if Error == False and r"\nDevice Apikey:" in line:
        UserFile.write("\nDevice Apikey: " + line[106:114])
    if Error == True and r"\nDevice Apikey:" in line:
        pass
####################################################################################################
def nextrowfinder(Current_Row):
    if "Login in success. id:" in Current_Row:
        KnowNextRow = "loginTapped() - Login Button - version:"
        return KnowNextRow
    elif "loginTapped() - Login Button - version:" in Current_Row:
        KnowNextRow = "logFoundBleNames() - Found bleNames:"
        return KnowNextRow
    elif "logFoundBleNames() - Found bleNames:" in Current_Row:
        KnowNextRow = "viewDidLoad() - viewDidLoad"
        return KnowNextRow
   # elif "viewDidLoad() - viewDidLoad" in Current_Row:
    #    KnowNextRow = "waitTimerSerialNumEvent(timer:) - Found VR Appliance:"
    #    return KnowNextRow
    elif "waitTimerSerialNumEvent(timer:) - Found VR Appliance:" in Current_Row:
        KnowNextRow = "wifiScanTimerEvent(timer:) - Wifi list requested. Name:"
        return KnowNextRow
    elif "wifiScanTimerEvent(timer:) - Wifi list requested. Name:" in Current_Row:
        KnowNextRow = "refrigeratorTapped() - segue_to_enter_pin_sid"
        return KnowNextRow
    elif "refrigeratorTapped() - segue_to_enter_pin_sid" in Current_Row:
        KnowNextRow = "viewDidLoad() - viewDidLoad"
        return KnowNextRow
    #elif "viewDidLoad() - viewDidLoad" in Current_Row:
     #   KnowNextRow = "applianceTapped() - segue_to_wifi_select_sid"
      #  return KnowNextRow
    elif "applianceTapped() - segue_to_wifi_select_sid" in Current_Row:
        KnowNextRow = "viewDidLoad() - viewDidLoad"
        return KnowNextRow
    #elif "viewDidLoad() - viewDidLoad" in Current_Row:
    #    KnowNextRow = "prepare(for:sender:) - segue_to_prod_wifi_setup_sid with:"
    #    return KnowNextRow
    elif "prepare(for:sender:) - segue_to_prod_wifi_setup_sid with:" in Current_Row:
        KnowNextRow = "viewDidLoad() - Got a valid mac:"
        return KnowNextRow
    elif "viewDidLoad() - Got a valid mac:" in Current_Row:
        KnowNextRow = "viewDidLoad() - viewDidLoad"
        return KnowNextRow
    #elif "viewDidLoad() - viewDidLoad" in Current_Row:
    #    KnowNextRow = "onRecordButton - wifi:"
    #    return KnowNextRow
    elif "onRecordButton - wifi:" in Current_Row:
        KnowNextRow = "addWifiNameToParamOut(wifi:) - Added WiFi name to apParamOut:"
        return KnowNextRow
    elif "addWifiNameToParamOut(wifi:) - Added WiFi name to apParamOut:" in Current_Row:
        KnowNextRow = "setDevicePrivilegeCloud(macAddress:userApiKey:devicePin:privilegeCompletionHandler:) - Called with: mac:"
        return KnowNextRow
    elif "setDevicePrivilegeCloud(macAddress:userApiKey:devicePin:privilegeCompletionHandler:) - Called with: mac:" in Current_Row:
        KnowNextRow = "setDevicePrivilegeCloud(macAddress:userApiKey:devicePin:privilegeCompletionHandler:) - \nDevice Apikey:"
        return KnowNextRow
    elif "setDevicePrivilegeCloud(macAddress:userApiKey:devicePin:privilegeCompletionHandler:) - \nDevice Apikey:" in Current_Row:
        KnowNextRow = "setPassphrase(psswd:) - Enter setPassphrase with  appliance.apParamOut.count:"
        return KnowNextRow
    elif "setPassphrase(psswd:) - Enter setPassphrase with  appliance.apParamOut.count:" in Current_Row:
        KnowNextRow = "onRecordButton - Calling updateApplianceRecord() after Cloud call"
        return KnowNextRow
    elif "onRecordButton - Calling updateApplianceRecord() after Cloud call" in Current_Row:
        KnowNextRow = "updateApplianceRecord() - updating appliance record: name: Optional"
        return KnowNextRow
    elif "updateApplianceRecord() - updating appliance record: name: Optional" in Current_Row:
        KnowNextRow = "setupChangeNotification() - Setup Complete (notification). Returning to the Product Select Screen now."
        return KnowNextRow
    elif "setupChangeNotification() - Setup Complete (notification). Returning to the Product Select Screen now." in Current_Row:
        KnowNextRow = "setupChangeNotification() - Calling updateApplianceRecord() in Notification call"
        return KnowNextRow
    elif "setupChangeNotification() - Calling updateApplianceRecord() in Notification call" in Current_Row:
        KnowNextRow = "End of Setup Log\n\n\n"
        return KnowNextRow
    elif "viewDidLoad() - viewDidLoad" in Current_Row:
        KnowNextRow = "View Load"
        return KnowNextRow
    else:
        KnowNextRow = "Error"
        return KnowNextRow
####################################################################################################




def main():
    list = create_connection(filename)  # create_connection(database)
    global Error
    #counter = 0
    cur = list.cursor()
    cur.execute("SELECT error_text from error_log ")
    rows = cur.fetchall()
    perlist = create_connection(perfect)
    percur = perlist.cursor()
    percur.execute("SELECT error_text from error_log Where id >= 2")
    perrows = percur.fetchall()

    #for row in rows:
    #   counter = counter + 1

    #for count in range(counter):

    rows_list = []
    perrows_list = []

    for row in rows:
        KnowNextRow = nextrowfinder(str(row))
        rows_list.append(KnowNextRow)

    for perrow in perrows:
        PerfectNextRow = perrow
        xx = (str(PerfectNextRow))
        perrows_list.append(xx)
    rows_len = len(rows_list)  # Get length of lists to ensure they are the same
    perlen = len(perrows_list)

    #print(rows_list)
    #print(perrows_list)

    for idx, Know_Next in enumerate(rows_list):
        if idx < (perlen - 1):  # Check that perrows item exists
            if Know_Next in perrows_list[idx]:
                #print("Match on line " + str(idx))
                pass

            else:
                print("View Did Load Screen")




main()

Я хочу получить номер модели, которую я пробовал переменной [start: end], но я получу его, только если пользователь установит точную длину строки.Я хотел бы выполнить поиск по ключевому слову и взять текст, следующий за ним.

Ответы [ 2 ]

0 голосов
/ 05 февраля 2019

В вашем тексте я могу найти только эти пять данных: имя пользователя, пароль, номер модели, macaddress и applname.Я создал регулярное выражение для именованных групп, чтобы вам было легко понять его содержание.Используемое регулярное выражение:

(?s)id: (?P<username>.+?) - (?P<password>.+?)'.*Appliance: (?P<modelnumber>\S+).*macAddress: (?P<macaddress>.+?)'.*appl name: (?P<applname>\S+)

Здесь (?s) предназначено для включения . в соответствие с новыми строками, а ваши данные, кажется, охватывают несколько строк.А остальные именованные группы располагаются в порядке появления данных.Если вам нужно найти дополнительную информацию в своем тексте, вы можете улучшить регулярное выражение для сбора дополнительной информации аналогичным образом или позвонить мне за помощью, если вам трудно.

Демо

Образцы кодов Python,

import re

s = '''[('loginTapped() - Login in success. id: fakeemail@gmail.com - Password123',), ('loginTapped() - Login Button - version: 1.03.29 (29)',), ('logFoundBleNames() - Found bleNames: , VR0796a3',), ('viewDidLoad() - viewDidLoad',), ('waitTimerSerialNumEvent(timer:) - Found XY Appliance: VR0796a3 and serial: macAddress: 0025ca0796a3',), ('wifiScanTimerEvent(timer:) - Wifi list requested. Name: VR0796a3',), ('refrigeratorTapped() - segue_to_enter_pin_sid',), ('viewDidLoad() - viewDidLoad',), ('applianceTapped() - segue_to_wifi_select_sid',), ('viewDidLoad() - viewDidLoad',), ('prepare(for:sender:) - segue_to_prod_wifi_setup_sid with: IotTest',), ('viewDidLoad() - Got a valid mac: 0025ca0796a3',), ('viewDidLoad() - viewDidLoad',), ('onRecordButton - wifi: IotTest',), ('addWifiNameToParamOut(wifi:) - Added WiFi name to apParamOut: IotTest',), ('setDevicePrivilegeCloud(macAddress:userApiKey:devicePin:privilegeCompletionHandler:) - Called with: mac: 0025ca0796a3 apiKey: 757d1040 devicePin: 1234',), ('setDevicePrivilegeCloud(macAddress:userApiKey:devicePin:privilegeCompletionHandler:) - \nDevice Apikey: c8b428e2\n',), ('setPassphrase(psswd:) - Enter setPassphrase with appliance.apParamOut.count: 38 - psswd len: 9',), ('onRecordButton - Calling updateApplianceRecord() after Cloud call',), ('updateApplianceRecord() - updating appliance record: name: Optional("XY0796a3") mac: 0025ca0796a3 serial: appl name: Optional("Freezer") modelID: 6',), ('setupChangeNotification() - Setup Complete (notification). Returning to the Product Select Screen now.',), ('setupChangeNotification() - Calling updateApplianceRecord() in Notification call',)]'''

m = re.search(r"(?s)id: (?P<username>.+?) - (?P<password>.+?)'.*Appliance: (?P<modelnumber>\S+).*macAddress: (?P<macaddress>.+?)'.*appl name: (?P<applname>\S+)", s)
if (m):
 print('username: {}, password: {}, modelnumber: {}, macaddress: {}, applname: {}'.format(m.group('username'),m.group('password'),m.group('modelnumber'),m.group('macaddress'),m.group('applname')))

Печатает запрашиваемую информацию,

username: fakeemail@gmail.com, password: Password123, modelnumber: VR0796a3, macaddress: 0025ca0796a3, applname: Optional("Freezer")
0 голосов
/ 05 февраля 2019

Попробуйте что-то вроде этого:

import re
m = re.search(r'Found XY Appliance:\s*([^,]*)', dblogstring)
m.group(0)

Соответствует тексту в скобках (), который является чем-то, что не является запятой.Он надежно извлечет части сложной строки, которая изменяется динамически.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...