TextCtrl to re.sub

In python I can write:

myregex = r’\sAnd\s’
s = re.sub(myregex,’ & ',‘Bake Beans And spam.txt’)
print s ## prints: Bake Beans & spam.txt

However using:

var = self.AdvanceReplace.GetValue()
f is filename: Bake Beans And spam.txt

TextCtrl contains r’\sAnd\s’
print var # Bake Beans And spam.txt
s = re.sub(var,’ & ',f)
print s # Bake Beans And spam.txt

How can I use my box to accept an regex?

···

Wow, this reads like a koan.

If you want to get a string from a wxTextCtrl, then using the .GetValue() method will, yes, in fact return a string. Then you can do whatever you want with that string.

I beg-to-differ

Here is my complete code. Add a folder with a text called “Bake Beans Amd spam.txt”
The bottom TextCtrl you can add an regex. r’\sAnd\s’
You will see that the regex will not accept the first agument as a string!

Wow, this reads like a koan.

If you want to get a string from a wxTextCtrl, then using the .GetValue() method will, yes, in fact return a string. Then you can do whatever you want with that string.

I even used Tim Roberts suggestion and got the same results.

-- coding: utf-8 --

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

class MainFrame(wx.Frame):
def init(self):
args = sys.argv[1:]
wx.Frame.init(self,None,wx.ID_ANY,
title=‘List and Correct Naming Files’,
size=(600, 450))
self.filenames = None

    self.hbox = wx.BoxSizer()
    self.hbox2 = wx.BoxSizer()
    self.hbox3 = wx.BoxSizer()
    self.hbox4 = wx.BoxSizer()
    self.vbox= wx.BoxSizer(wx.VERTICAL)
   
    self.background = wx.Panel(self)
    
    self.OpenDir = wx.TextCtrl(self.background,style=wx.PROCESS_ENTER)
    self.OpenDir.Bind(wx.EVT_LEFT_UP,self.OnChooseRoot)              
    self.Detector = wx.TextCtrl(self.background,style=wx.PROCESS_ENTER)       
    self.BasicRemove = wx.TextCtrl(self.background,style=wx.PROCESS_ENTER)
    self.BasicReplace = wx.TextCtrl(self.background,style=wx.PROCESS_ENTER)
    self.AdvanceReplace = wx.TextCtrl(self.background,style=wx.PROCESS_ENTER)
   
    self.middleview = wx.TextCtrl(self.background,style = wx.TE_MULTILINE|wx.TE_RICH)
    self.bottomview = wx.TextCtrl(self.background,style = wx.TE_MULTILINE|wx.TE_RICH)

    self.butExport = wx.Button(self.background,wx.ID_ANY,label = 'write to text')       
    self.butExport2 = wx.Button(self.background,wx.ID_ANY,label = 'rename')
    self.butClear = wx.Button(self.background,wx.ID_ANY,label = 'clear')       
    self.Bind(wx.EVT_BUTTON, self.checkBtnClick, self.butExport)
    self.Bind(wx.EVT_BUTTON, self.checkBtnClick2, self.butExport2)
    self.Bind(wx.EVT_BUTTON, self.OnClear, self.butClear)
    self.Bind(wx.EVT_TEXT_ENTER, self.TxtEnter, self.BasicRemove)
    self.Bind(wx.EVT_TEXT_ENTER, self.TxtEnter, self.BasicReplace)
    self.BasicRemove.Bind(wx.EVT_TEXT_ENTER, self.TxtEnter)
    self.BasicReplace.Bind(wx.EVT_TEXT_ENTER, self.TxtEnter)
    self.AdvanceReplace.Bind(wx.EVT_TEXT_ENTER, self.checkBtnClick2)
   
    self.hbox.Add(self.OpenDir,proportion = 1, border=0)
    self.hbox.Add(self.butExport,proportion = 0,border=0)
    self.hbox.Add(self.butClear,proportion = 0,border=0)

    self.hbox3.Add(self.BasicRemove,proportion = 1,border=0)
    self.hbox3.Add(self.BasicReplace,proportion = 1,border=0)
    self.hbox4.Add(self.AdvanceReplace,proportion = 0,border=0)
   
    self.hbox2.Add(self.Detector,proportion = 3,border=0)        
    self.hbox2.Add(self.butExport2,proportion = 0,border=0)       
   
    self.vbox.Add(self.hbox,proportion = 0,flag = wx.EXPAND,border=0)
    self.vbox.Add(self.middleview,proportion = 2,flag = wx.EXPAND,border=0)
    self.vbox.Add(self.hbox2,proportion = 0,flag = wx.EXPAND,border=0)
    self.vbox.Add(self.hbox3,proportion = 0,flag = wx.EXPAND,border=0)
    self.vbox.Add(self.hbox4,proportion = 0,flag = wx.EXPAND,border=0)
    self.vbox.Add(self.bottomview,proportion = 1,flag = wx.EXPAND,border=0)

    self.background.SetSizer(self.vbox)
    self.Show()
    font1 = wx.Font(10, wx.SWISS, wx.ITALIC, wx.LIGHT, False, u'Courier New')
    self.OpenDir.SetFont(font1)
    self.OpenDir.SetForegroundColour((140,140,140))       
    self.OpenDir.SetValue("Click here to open directory")
    font4 = wx.Font(10, wx.SWISS, wx.ITALIC, wx.LIGHT, False, u'Courier New')
    self.Detector.SetFont(font4)
    self.Detector.SetForegroundColour((140,140,140))                   
    self.Detector.SetValue("commas in naming will be detected")

def OnChooseRoot(self, event):
    self.middleview.Clear()
    with wx.DirDialog(self, "Choose a directory:",
                       style=wx.DD_DEFAULT_STYLE) as dlg:
        if dlg.ShowModal() == wx.ID_OK:
            for self.dirname, self.dirnames, self.filenames in os.walk(dlg.GetPath()):               
                for self.filename in self.filenames:
                    font1 = wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL, False, u'Courier New')
                    self.middleview.SetFont(font1)
                    s=('\n')
                    bs=(os.path.join(self.filename,s))
                    bf = (bs.replace("\\",""))
                    self.middleview.AppendText(bf)
                    font3 = wx.Font(8, wx.MODERN, wx.NORMAL, wx.NORMAL, False, u'Courier New')
                    self.OpenDir.SetFont(font3)
                    self.OpenDir.SetFont(font3)
                    self.OpenDir.SetForegroundColour((0,0,0))                       
                    self.OpenDir.SetValue(self.dirname)
                   
        for self.dirname, self.dirnames, self.filenames in os.walk(dlg.GetPath()):               
            for self.filename in self.filenames:
                if ',' in self.filename:
                    font4 = wx.Font(8, wx.SWISS, wx.ITALIC, wx.LIGHT, False, u'Courier New')
                    self.Detector.SetFont(font4)
                    self.Detector.SetForegroundColour((250,100,100))                          
                    self.Detector.SetValue("errors detected in naming")
                    font2 = wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL, False, u'Courier New')
                    self.bottomview.SetFont(font2)
                    s=('\n')                   
                    bs=(os.path.join(self.filename,s))
                    bf = (bs.replace("\\",""))
                    self.bottomview.AppendText(bf)
                   
def checkBtnClick(self, bg):
    dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.txt", \
            wx.SAVE | wx.OVERWRITE_PROMPT)
    if dlg.ShowModal() == wx.ID_OK:
        bg = self.middleview.GetValue()           
        self.filename=dlg.GetFilename()
        self.dirname=dlg.GetDirectory()
        filehandle=open(os.path.join(self.dirname, self.filename),'w')
        filehandle.write("FileList\n"+(bg))
        v =("\\")
        b= self.filename
        self.OpenDir.SetValue(self.dirname + v + b)

        font4 = wx.Font(8, wx.MODERN, wx.NORMAL, wx.NORMAL, False, u'Courier New')
        self.OpenDir.SetFont(font4)
        self.OpenDir.SetFont(font4)
        self.OpenDir.SetForegroundColour((0,0,0))
    self.butExport.SetLabel("written")
   
def OnClear(self, event):
    self.middleview.Clear()
    self.OpenDir.Clear()
    self.OpenDir.SetValue("click here to load a folder again")
    self.bottomview.Clear()
    font4 = wx.Font(10, wx.SWISS, wx.ITALIC, wx.LIGHT, False, u'Courier New')
    self.Detector.SetFont(font4)
    self.Detector.SetForegroundColour((140,140,140))       
    self.Detector.SetValue("commas in naming will be detected")
    self.BasicRemove.Clear()
    self.BasicReplace.Clear()
    self.BasicRemove.SetValue("string to remove")
    self.BasicReplace.SetValue("string to replace")    

def TxtEnter(self, event):
    self.AdvanceReplace.GetValue()
    self.BasicRemove.SetValue('')
    event.Skip()           
    self.BasicRemove.GetValue()
    self.BasicReplace.SetValue('')
    event.Skip()
    self.BasicReplace.GetValue()
   
def TxtEnter2(self, event):
    pass

def checkBtnClick2(self, func):
            if self.filenames:
                    path = self.dirname
                    dirList=os.listdir(path)                       
                    for self.filename in dirList:
                            f = self.filename
                            print self.AdvanceReplace.GetValue()

if not f.startswith(‘.’) and f.find(self.AdvanceReplace.GetValue()) >= 0:

print self.AdvanceReplace

print f

                            var = self.AdvanceReplace.GetValue()                               
                            print var, "     print v"
                            s = re.sub(var,' & ',f)
                            print s, "     print s"

os.rename(os.path.join(self.dirname, f), os.path.join(self.dirname,f.replace(self.BasicRemove.GetValue(),self.BasicReplace.GetValue())))

os.rename(os.path.join(self.dirname, f), os.path.join(self.dirname,s))

                            print f, "     print f"
            self.butExport2.SetLabel("renamed")
            font4 = wx.Font(10, wx.SWISS, wx.ITALIC, wx.LIGHT, False, u'Courier New')
            self.Detector.SetFont(font4)
            self.Detector.SetForegroundColour((40,140,40))               
            self.Detector.SetValue("files are re-written, check directory")
            self.bottomview.Clear()
            self.middleview.Clear()
            self.middleview.SetValue("click clear and load again")

if name == ‘main’:
import wx.lib.mixins.inspection as WIT
app = WIT.InspectableApp(redirect=True)
frame = MainFrame()
frame.Show()
app.MainLoop()

···

On Tuesday, August 20, 2013 9:19:18 PM UTC-5, Che M wrote:

I have a type error: Bake Beans And spam

···

On Tuesday, August 20, 2013 8:35:56 PM UTC-5, George McCown wrote:

In python I can write:

myregex = r’\sAnd\s’
s = re.sub(myregex,’ & ',‘Bake Beans And spam.txt’)
print s ## prints: Bake Beans & spam.txt

However using:

var = self.AdvanceReplace.GetValue()
f is filename: Bake Beans And spam.txt

TextCtrl contains r’\sAnd\s’
print var # Bake Beans And spam.txt
s = re.sub(var,’ & ',f)
print s # Bake Beans And spam.txt

How can I use my box to accept an regex?

George,

In python I can write:

myregex = r'\sAnd\s'
s = re.sub(myregex,' & ','Bake Beans And spam.txt')
print s ## prints: Bake Beans & spam.txt

However using:

var = self.AdvanceReplace.GetValue()
f is filename: Bake Beans And spam.txt

TextCtrl contains r'\sAnd\s'
print var # Bake Beans And spam.txt
s = re.sub(var,' & ',f)
print s # Bake Beans And spam.txt

var = Bake Beans And spam.txt
f = Bake Beans And spam.txt

Use meaningful names for controls, methods, variables etc and it will help you.

Your first sample is better:
s = re.sub(myregex,' & ','Bake Beans And spam.txt')

so change that to:
s = re.sub(myregex, ' & ', filename)

And use a debugger to step through your code and make sure that the variables really contain what you think they contain.

                                 var = self.AdvanceReplace.GetValue()
                                 print var, " print v"
                                 s = re.sub(var,' & ',f)
                                 print s, " print s"

In your full script you have the above, verify with the debugger that at this point "var" contains "r'\sAnd\s'"

Werner

···

On 21/08/2013 03:35, George McCown wrote:

r’\sAnd\s’ print v
Baked Beans And Spam.txt print s
Baked Beans And Spam.txt print f

Thats what I’ve been doing. s is allways holding Baked Beans And Spam.txt

I’m thinking that the TextCtrl is not meant to pass a function like regex

···

On Wednesday, August 21, 2013 1:02:54 AM UTC-5, werner wrote:

George,

On 21/08/2013 03:35, George McCown wrote:

In python I can write:

myregex = r’\sAnd\s’

s = re.sub(myregex,’ & ',‘Bake Beans And spam.txt’)

print s ## prints: Bake Beans & spam.txt

However using:

var = self.AdvanceReplace.GetValue()

f is filename: Bake Beans And spam.txt

TextCtrl contains r’\sAnd\s’

print var # Bake Beans And spam.txt

s = re.sub(var,’ & ',f)

print s # Bake Beans And spam.txt

var = Bake Beans And spam.txt

f = Bake Beans And spam.txt

Use meaningful names for controls, methods, variables etc and it will
help you.

Your first sample is better:

s = re.sub(myregex,’ & ',‘Bake Beans And spam.txt’)

so change that to:

s = re.sub(myregex, ’ & ', filename)

And use a debugger to step through your code and make sure that the
variables really contain what you think they contain.

                             var = self.AdvanceReplace.GetValue()

                             print var, "     print v"

                             s = re.sub(var,' & ',f)

                             print s, "     print s"

In your full script you have the above, verify with the debugger that at
this point “var” contains “r’\sAnd\s’”

Werner

Hi George,

r'\sAnd\s' print v
Baked Beans And Spam.txt print s
Baked Beans And Spam.txt print f
Thats what I've been doing. s is allways holding Baked Beans And Spam.txt
I'm thinking that the TextCtrl is not meant to pass a function like regex

I doubt that this is your problem.

But frankly I can't follow this thread anymore - what are your comments above relate to? Please use interspersed format, i.e. put the relevant comment below the text you are commenting on and maybe this way we get a bit further.

I suggest you create a small runnable application which just has hard coded the above values - i.e. not be dependend on some file on disk or whatever.

Werner

···

On 21/08/2013 16:53, George McCown wrote:

Hi George,

here a small sample, hope it helps

Werner

smallSample.py (1.15 KB)

...
Hi,
I confess, I am almost lost in the code as well as in the further
comments, but just in case it could be the issue here:
the raw string form like:
r'\sAnd\s'
is meant to be used in the source code - apostrophes to delimit
string, r-prefix the avoid special evaluation of backslash (or you can
use '\\sAnd\\s' .

In the gui textcontrol like wx.TextCtrl the above would be displayed just as
\sAnd\s
and the GetValue call will return the same pattern string.

hth,
  vbr

···

2013/8/21 George McCown <georgemccown@gmail.com>:

r'\sAnd\s' print v
Baked Beans And Spam.txt print s
Baked Beans And Spam.txt print f
Thats what I've been doing. s is allways holding Baked Beans And Spam.txt
I'm thinking that the TextCtrl is not meant to pass a function like regex

On Wednesday, August 21, 2013 1:02:54 AM UTC-5, werner wrote:

George,

On 21/08/2013 03:35, George McCown wrote:
> In python I can write:
>
> myregex = r'\sAnd\s'
> s = re.sub(myregex,' & ','Bake Beans And spam.txt')
> print s ## prints: Bake Beans & spam.txt
>
> However using:
>
> var = self.AdvanceReplace.GetValue()
> f is filename: Bake Beans And spam.txt
>
> TextCtrl contains r'\sAnd\s'

werner wrote:

Hi George,

here a small sample, hope it helps

Here's an even smaller sample, showing that it works. Please note that
I tested the code I send you yesterday.

C:\tmp>python
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

import re
rex = r'\sAnd\s'
rep = ' & '
str = 'Baked Beans And Spam.txt'
print re.sub( rex, rep, str )

Baked Beans & Spam.txt

···

--
Tim Roberts, timr@probo.com
Providenza & Boekelheide, Inc.

werner wrote:

Hi George,

here a small sample, hope it helps

Your example "smallSample.py" works perfectly for me. What's the problem?

···

--
Tim Roberts, timr@probo.com
Providenza & Boekelheide, Inc.

Hopefully nothing;-) , but then it is George who has the problem and I hoped that my little test shows that textctrl's can be used with all this without a problem, but then I might miss understand the problem George has.

Werner

···

On 21/08/2013 18:59, Tim Roberts wrote:

werner wrote:

Hi George,

here a small sample, hope it helps

Your example "smallSample.py" works perfectly for me. What's the problem?

werner wrote:

Hopefully nothing;-) , but then it is George who has the problem and I
hoped that my little test shows that textctrl's can be used with all
this without a problem, but then I might miss understand the problem
George has.

My apologies. In all the confusion, I forgot who was who.

···

--
Tim Roberts, timr@probo.com
Providenza & Boekelheide, Inc.

I adjusted your sample to relate to my problem. Enter a regex in the second TextCtrl and you will see that

that self.regEx = wx.TextCtrl is not passing a regex function. The user enters regex.

I hope this states my problem better.

smallSample3.py (1.44 KB)

···

On Wednesday, August 21, 2013 12:07:16 PM UTC-5, werner wrote:

On 21/08/2013 18:59, Tim Roberts wrote:

werner wrote:

Hi George,

here a small sample, hope it helps

Your example “smallSample.py” works perfectly for me. What’s the problem?

Hopefully nothing;-) , but then it is George who has the problem and I
hoped that my little test shows that textctrl’s can be used with all
this without a problem, but then I might miss understand the problem
George has.

Werner

Hi George,

I adjusted your sample to relate to my problem. Enter a regex in the second TextCtrl and you will see that
that self.regEx = wx.TextCtrl is not passing a regex function. The user enters regex.

What exactly is being entered into the TextCtrl?

I hope this states my problem better.

I didn't know how to do that but reading the earlier post of Vlastimil gave me the hint.

So attached a modified version which works for me.

Werner

smallSample.py (1.31 KB)

···

On 21/08/2013 19:46, George McCown wrote:

George McCown wrote:

I adjusted your sample to relate to my problem. Enter a regex in the
second TextCtrl and you will see that
that self.regEx = wx.TextCtrl is not passing a regex function. The
user enters regex.
I hope this states my problem better.

There is no such thing as a "regex function". A regular expression is
just a string that happens to use some special characters. That string
gets passed to the re.sub function, which processes it.

Your sample code also works just fine. If I type \sAnd\s in the box,
the substitution happens. So, what is the problem?

By the way, this is silly:
    c = Sample(None)
    with c as dlg:
        dlg.ShowModal()

The whole point of the "with" block is ti make sure the object doesn't
exist when the "with" is completed. You should just do this:
    with Sample(None) as dlg:
        dlg.ShowModal()

(Although my version of wx doesn't support that yet.)

···

--
Tim Roberts, timr@probo.com
Providenza & Boekelheide, Inc.

My-bad, I was including the quotes outside the regular expression.

···

On Wednesday, August 21, 2013 1:16:58 PM UTC-5, Tim Roberts wrote:

George McCown wrote:

I adjusted your sample to relate to my problem. Enter a regex in the

second TextCtrl and you will see that

that self.regEx = wx.TextCtrl is not passing a regex function. The

user enters regex.

I hope this states my problem better.

There is no such thing as a “regex function”. A regular expression is

just a string that happens to use some special characters. That string

gets passed to the re.sub function, which processes it.

Your sample code also works just fine. If I type \sAnd\s in the box,

the substitution happens. So, what is the problem?

By the way, this is silly:

c = Sample(None)

with c as dlg:

    dlg.ShowModal()

The whole point of the “with” block is ti make sure the object doesn’t

exist when the “with” is completed. You should just do this:

with Sample(None) as dlg:

    dlg.ShowModal()

(Although my version of wx doesn’t support that yet.)


Tim Roberts, ti...@probo.com

Providenza & Boekelheide, Inc.

Great that things work for you now.
Obviously much nicer, in my “defense” this is a copy/paste thingy where I didn’t
think much, in my case the code is normally:
c = Sample(None)
… do other stuff to init this thing
with c.view as dlg:

now do the view init and show it

    dlg.ShowModal()

I think the “with” context manager support for Dialog etc has been
added as of 2.8.11.0 - a loooooooooooong time ago.
Werner

···

Hi George and Tim,

  On 21/08/2013 21:21, George McCown wrote:
      My-bad,  I was including the quotes outside the regular

expression.

      On Wednesday, August 21, 2013 1:16:58 PM UTC-5, Tim Roberts

wrote:

      By the way,

this is silly:

          c = Sample(None)


          with c as dlg:


              dlg.ShowModal()




      The whole point of the "with" block is ti make sure the object

doesn’t

      exist when the "with" is completed.  You should just do this:


          with Sample(None) as dlg:


              dlg.ShowModal()
    :-)

Then I just missed it – I have 2.8.10.1. wx is not part of my
daily battles, so I don’t upgrade regularly.

···

werner wrote:

      c = Sample(None)

      .... do other stuff to init this thing

      with c.view as dlg: # now do the view init and show it

          dlg.ShowModal()



  I think the "with" context manager support for Dialog etc has been

added as of 2.8.11.0 - a loooooooooooong time ago.

-- Tim Roberts, Providenza & Boekelheide, Inc.

timr@probo.com