Python:在动态文本中查找字符串,然后在该行的前面放置另一个文本

问题描述 投票:0回答:1

我已经尝试找到/构建解决方案,但目前对我来说太复杂了。我有一个来自SAP的文本(存储在tkinter的scrooledtext中。

session.findById("wnd[0]").sendVKey 4
session.findById("wnd[1]/tbar[0]/btn[17]").press
session.findById("wnd[1]/usr/tabsG_SELONETABSTRIP/tabpTAB001/ssubSUBSCR_PRESEL:SAPLSDH4:0220/sub:SAPLSDH4:0220/ctxtG_SELFLD_TAB-LOW[3,24]").setFocus
session.findById("wnd[1]").sendVKey 0
session.findById("wnd[1]/usr/lbl[1,1]").setFocus
session.findById("wnd[1]").sendVKey 33

我想在出现.sendVKey时查找每一行,并将newtext放在该行的开头(或该行的上方)-例如,示例中有3行:

在出现sendkey文本之前添加了新文本!session.findById(“ wnd [0]”)。sendVKey 4

(...)在sendkey文本出现之前添加了新文本!session.findById(“ wnd [1]”)。sendVKey 0

(...)

尝试使用re.sub,re.findall和replace,但是我认为这不是一个好方法。我的工作代码在下面,但是不是动态的(在.sendVkey方法中,它可以是(“ wnd [1]”)中的其他窗口(0、1、2、3等)。任何提示/解决方案吗?请帮助:(

    def multiple_replace(string, rep_dict):
        pattern = re.compile("|".join([re.escape(k) for k in sorted(rep_dict, key=len, reverse=True)]), flags=re.DOTALL)
        return pattern.sub(lambda x: rep_dict[x.group(0)], string)


    date_div = RPAcode.get("1.0", tk.END)
    delay_vba_function = "   Added new text before sendkey text occurs"
"
    replaced_text = multiple_replace(date_div, {'.sendVKey' : '\n' + delay_vba_function + '\n' + '.sendVKey', \
                                                'session.findById("wnd[1]").sendVKey' : '\n' + delay_vba_function + '\n' + 'session.findById("wnd[1]").sendVKey', \
                                                'session.findById("wnd[2]").sendVKey' : '\n' + delay_vba_function + '\n' + 'session.findById("wnd[2]").sendVKey', \
                                                'session.findById("wnd[3]").sendVKey' : '\n' + delay_vba_function + '\n' + 'session.findById("wnd[3]").sendVKey'})
    #print(replaced_text)

    RPAcode.delete('0.0', tk.END) #Deletes previous data
    RPAcode.insert(1.0, replaced_text)
python regex replace find findall
1个回答
0
投票
text = 'session.findById("wnd[0]").sendVKey 4' if '.sendVKey' in text: text = '(...)' + text text

如果您在终端中运行它,输出将是:

'(...)session.findById("wnd[0]").sendVKey 4'

因此,如您所见,脚本甚至在文本行的前面已经添加了一些文本。如果您不说text = '(...)' + text,而是说text = '(...)\n' + text,则(...)将显示在实际文本上方的一行中。如果将上述代码示例放入遍历所有文本行的for循环中,我认为该方法可能会解决您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.