python - 如何从长度变化的字符串中获取特定文本?
问题描述
我有一个字符串,其中包含我想提取的信息。我的问题是字符串长度可以根据产品版本、用户名、密码等而改变。因此我不能只说变量[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: ) - 请求的 Wifi 列表。名称: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:) - 添加 WiFi 名称到 apParamOut: IotTest',), ('setDevicePrivilegeCloud(macAddress:userApiKey:devicePin:privilegeCompletionHandler:) - 调用:mac: 0025ca0796a3 apiKey: 757d1040 devicePin: 1234',), ('setDevicePrivilegeCloud(macAddress:userApiKey:devicePin:privilegeCompletionHandler:) - \nDevice Apikey: c8b428e2\n',), ('setPassphrase(psswd:) - 输入 setPassphrase with appliance.apParamOut.count: 38 - psswd len: 9',), ('onRecordButton - 云调用后调用 updateApplianceRecord()',), ('updateApplianceRecord() - 更新设备记录:名称:可选(“XY0796a3”)mac:0025ca0796a3 序列号:应用程序名称: Optional("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],但只有当用户放置一个确切的字符串长度时,我才会得到它。我想对关键字进行某种搜索并抓取它后面的文本。
解决方案
我只能在您给定的文本中找到这五个信息,它们是用户名、密码、型号、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")
推荐阅读
- reactjs - 在路由中传递动态 URL
- java - 为什么 CompletableFuture 是线程安全的?
- javascript - 如何检查元素是否包含至少一个直接文本节点
- random - Neo4j:匹配随机节点时,with子句中rand()和rand()之间的区别
- r - 如何在不输入所有列名的情况下添加列?
- android - AdMob 横幅的默认尺寸是多少?
- teradata - 关于唯一主键与唯一主索引的问题
- ruby-on-rails - 在 html.erb 中完成了几个月的渲染
- multithreading - 带有 CompletableFuture 的 Spring-Boot App,如何管理大量请求?
- google-sheets - Countif 区分大小写的谷歌表格