Adapting this code from Levi?

Moderator: Kathy_9

terrypin
Posts: 489
Joined: Tue Jun 29, 2010 9:51 am
operating_system: Windows 10
System_Drive: C
32bit or 64bit: 64 Bit
motherboard: Asus Z170 Pro 4
processor: Intel Core i7 6700K 4.0GHz
ram: 32 GB
Video Card: None - uses built-in graphics
sound_card: HD onboard sound card
Hard_Drive_Capacity: 4.256 TB
Monitor/Display Make & Model: iLyama Prolite E2403WS 24" 1920x1200
Corel programs: Paint Shop Pro 8; Paint Shop Pro 2018
Location: East Grinstead UK

Adapting this code from Levi?

Post by terrypin »

Almost all of the script below was written for me (a non-programmer) by LeviFiction years ago, and I've been delighted with its reliability ever since. I now need an almost identical script, but instead of pasting text from its location on the Windows Clipboard, I want the script to get it from either of these:

- a certain line and position in the text file C:\Users\terry\Dropbox\FinishedWalks\Source.txt

- the last occupied cell of column I in the Excel worksheet C:\Users\terry\Dropbox\FinishedWalks\WalkIndex.xlsm

If that is technically possible I'd much appreciate help please.

Code: Select all

from JascApp import *
from Tkinter import Tk

def ScriptProperties():
    return {
        'Author': u'Terry Pinnell',
        'Copyright': u'',
        'Description': u'',
        'Host': u'Paint Shop Pro',
        'Host Version': u'8.10'
        }

def Do(Environment):
    # EnableOptimizedScriptUndo
    App.Do( Environment, 'EnableOptimizedScriptUndo', {
           
            })
    # ASSUMES THAT VALUE OF MILES IS ON CLIPBOARD
    # ******************************************************
    
    # Text
    App.Do( Environment, 'Text', {
            'CreateAs': App.Constants.CreateAs.Vector,
            'Segments': [{
                'Bold': App.Constants.Boolean.true,
                'Fill': {
                    'Color': (0,0,0),
                    'Pattern': None,
                    'Gradient': None,
                    'Texture': None,
                    'Identity': u'Material'
                    },
                'Font': u'Arial',
                'LineStyle': {
                    'Name': u'',
                    'FirstCap': (u'Butt',0.25,0.25),
                    'LastCap': (u'Butt',0.25,0.25),
                    'FirstSegCap': (u'',0.25),
                    'LastSegCap': (u'',0.25),
                    'UseSegmentCaps': App.Constants.Boolean.false,
                    'Segments': []
                    },
                'LineWidth': 0,
                'PointSize': 36,
                'Start': (1460.5,314.5),
                'Stroke': {
                    'Color': None,
                    'Pattern': None,
                    'Gradient': None,
                    'Texture': None,
                    'Identity': u'Material'
                    }
                },{
                'Antialias': App.Constants.Boolean.true,
                'WarpText': App.Constants.Boolean.true,
                'AutoKern': App.Constants.Boolean.true,
                'Bold': App.Constants.Boolean.true,
                'Kerning': 0,
                'Leading': 0,
                'Fill': {
                    'Color': (0,0,0),
                    'Pattern': None,
                    'Gradient': None,
                    'Texture': None,
                    'Identity': u'Material'
                    },
                'Font': u'Arial',
                'Italic': App.Constants.Boolean.false,
                'Join': App.Constants.JointStyle.Miter,
                'LineStyle': {
                    'Name': u'',
                    'FirstCap': (u'Butt',0.25,0.25),
                    'LastCap': (u'Butt',0.25,0.25),
                    'FirstSegCap': (u'',0.25),
                    'LastSegCap': (u'',0.25),
                    'UseSegmentCaps': App.Constants.Boolean.false,
                    'Segments': []
                    },
                'LineWidth': 0, 
                'MiterLimit': 10,
                'PointSize': 36,     
                'SetText': App.Constants.Justify.Left,
                'Start': (1460.5,314.5),
                'Strikethru': App.Constants.Boolean.false,
                'Stroke': {
                    'Color': (255,255,255),
                    'Pattern': None,
                    'Gradient': None,
                    'Texture': None,
                    'Identity': u'Material'
                    },
                'Underline': App.Constants.Boolean.false
                },{
                'Characters': getText()
                }],
            'SavedText': None,
            'FinalApply': App.Constants.Boolean.false,
            'Matrix': None,
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Default,
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            })
    # SelectNone
    App.Do( Environment, 'SelectNone', {
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Default, 
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            })

def getText():
    r = Tk()
    text = r.selection_get(selection='CLIPBOARD')
    r.withdraw()
    r.update()
    r.destroy()
    return text
Terry
--
Terry, East Grinstead, UK
Using PSP 8 & PSP 2018 under Win 10
LeviFiction
Advisor
Posts: 6472
Joined: Thu Oct 02, 2008 1:07 pm
operating_system: Windows 10
System_Drive: C
32bit or 64bit: 64 Bit
motherboard: Alienware M17xR4
processor: Intel Core i7-3630QM CPU - 2_40GH
ram: 6 GB
Video Card: NVIDIA GeForce GTX 660M
sound_card: Sound Blaster Recon3Di
Hard_Drive_Capacity: 500GB
Corel programs: PSP: 8-2023
Location: USA

Re: Adapting this code from Levi?

Post by LeviFiction »

Is this still meant for use in PSP8? The big thing would be replacing the "getText()" function and inputting the correct parameters either by asking the user or by hardcoding it into the script.

Retrieving lines from a regular text file is fairly easy.

Code: Select all

def getText(filename, SpecificLine, SpecificCharacterIndex)
    f = open(filename, 'r')
    lines = f.readlines()
    f.close()
    return lines[SpecificLine][SpecificCharacterIndex:]  #Returns everything in the specific line after the characterindex to the end of the line
Excel may not be doable as I don't believe there are any built in scripts for working with Excel inside of Python. However CSV is doable if a little harder in PSP8. You wouldn't say Column I you'd say column 8 as CSVs don't use column lettering like Excel does and everything is 0 indexed so ColumnA = 0, ColumnB = 1 etc. But it would look something like this, fine-tuning might be needed.

Code: Select all

def getText(filename, rowNum, columnNum, delimiter=","):
    #Use a RowNum of -1 to get the last Column with a value
    f = open(filename, 'r')
    lines = f.readlines()
    f.close()
    columnValues = []
    if rowNum != -1: #A specific Row was requested
        return lines[rowNum].split(delimiter)[columnNum]
    #if we're here they want the last row with a value in that column
    for line in lines:
        columns = line.split(delimiter)
        if columns[columnNum]:
            columnValues.append(columns[columnNum])
    return columnValues[-1]
I have not tested either of these but they should work if I'm remembering everything correctly.
terrypin
Posts: 489
Joined: Tue Jun 29, 2010 9:51 am
operating_system: Windows 10
System_Drive: C
32bit or 64bit: 64 Bit
motherboard: Asus Z170 Pro 4
processor: Intel Core i7 6700K 4.0GHz
ram: 32 GB
Video Card: None - uses built-in graphics
sound_card: HD onboard sound card
Hard_Drive_Capacity: 4.256 TB
Monitor/Display Make & Model: iLyama Prolite E2403WS 24" 1920x1200
Corel programs: Paint Shop Pro 8; Paint Shop Pro 2018
Location: East Grinstead UK

Re: Adapting this code from Levi?

Post by terrypin »

Wow, thanks, that was quick!

Yes, still for PSP 8

It would have been astonishing if I'd interpreted/transcribed that 100% correctly and the script had run first time. But I got the message:
"The script could not be loaded"
Line 124 is
def getText(C:\Users\terry\Dropbox\FinishedWalks\Source.txt, 12, 21)

Here's the script output:

Executing RunScript
File "<string>", line 124
def getText(C:\Users\terry\Dropbox\FinishedWalks\Source.txt, 12, 21)
^
SyntaxError: invalid syntax

And here's my revised code; I've changed only the end section, apart from comments.

Code: Select all

# ATTEMPT #1 TO CHANGE USING TEXT FILE
# ************************************


from JascApp import *
from Tkinter import Tk

def ScriptProperties():
    return {
        'Author': u'Terry Pinnell',
        'Copyright': u'',
        'Description': u'',
        'Host': u'Paint Shop Pro',
        'Host Version': u'8.10'
        }

def Do(Environment):
    # EnableOptimizedScriptUndo
    App.Do( Environment, 'EnableOptimizedScriptUndo', {
           
            })
    # ASSUMES THAT VALUE OF MILES (%tMiles%) IS ON CLIPBOARD
    # ******************************************************
    
    # Text
    App.Do( Environment, 'Text', {
            'CreateAs': App.Constants.CreateAs.Vector,
            'Segments': [{
                'Bold': App.Constants.Boolean.true,
                'Fill': {
                    'Color': (0,0,0),
                    'Pattern': None,
                    'Gradient': None,
                    'Texture': None,
                    'Identity': u'Material'
                    },
                'Font': u'Arial',
                'LineStyle': {
                    'Name': u'',
                    'FirstCap': (u'Butt',0.25,0.25),
                    'LastCap': (u'Butt',0.25,0.25),
                    'FirstSegCap': (u'',0.25),
                    'LastSegCap': (u'',0.25),
                    'UseSegmentCaps': App.Constants.Boolean.false,
                    'Segments': []
                    },
                'LineWidth': 0,
                'PointSize': 36,
                'Start': (1460.5,314.5),
                'Stroke': {
                    'Color': None,
                    'Pattern': None,
                    'Gradient': None,
                    'Texture': None,
                    'Identity': u'Material'
                    }
                },{
                'Antialias': App.Constants.Boolean.true,
                'WarpText': App.Constants.Boolean.true,
                'AutoKern': App.Constants.Boolean.true,
                'Bold': App.Constants.Boolean.true,
                'Kerning': 0,
                'Leading': 0,
                'Fill': {
                    'Color': (0,0,0),
                    'Pattern': None,
                    'Gradient': None,
                    'Texture': None,
                    'Identity': u'Material'
                    },
                'Font': u'Arial',
                'Italic': App.Constants.Boolean.false,
                'Join': App.Constants.JointStyle.Miter,
                'LineStyle': {
                    'Name': u'',
                    'FirstCap': (u'Butt',0.25,0.25),
                    'LastCap': (u'Butt',0.25,0.25),
                    'FirstSegCap': (u'',0.25),
                    'LastSegCap': (u'',0.25),
                    'UseSegmentCaps': App.Constants.Boolean.false,
                    'Segments': []
                    },
                'LineWidth': 0, 
                'MiterLimit': 10,
                'PointSize': 36,     
                'SetText': App.Constants.Justify.Left,
                'Start': (1460.5,314.5),
                'Strikethru': App.Constants.Boolean.false,
                'Stroke': {
                    'Color': (255,255,255),
                    'Pattern': None,
                    'Gradient': None,
                    'Texture': None,
                    'Identity': u'Material'
                    },
                'Underline': App.Constants.Boolean.false
                },{
                'Characters': getText()
                }],
            'SavedText': None,
            'FinalApply': App.Constants.Boolean.false,
            'Matrix': None,
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Default,
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            })
    # SelectNone
    App.Do( Environment, 'SelectNone', {
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Default, 
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            })


# NEW CODE
# --------
# filename = C:\Users\terry\Dropbox\FinishedWalks\Source.txt
# Its 12th line is
# Distance = tMiles = 5.6
# and '5.6' occupies the three character positions 21-23 (which are the last chars on the line)

def getText(C:\Users\terry\Dropbox\FinishedWalks\Source.txt, 12, 21)
    f = open(C:\Users\terry\Dropbox\FinishedWalks\Source.txt, 'r')
    lines = f.readlines()
    f.close()
    return lines[12][20:]  #Returns everything in the specific line after the characterindex to the end of the line
Here also is the full file Source.txt

Code: Select all

GPX file name = tFileName = 20210623Ashurst-J-u452-m5.6.gpx

Track description = tTrackDescr = Circular walk with Janet, Ashurst

Track name = tTrackName = 20210623Ashurst-J-u452-m5.6
Walk date = tResult = Wednesday 23 June 2021
Date for later use =  tDatePrefix = 20210623

Start = tStartCropped = 13:15
End = tEndCropped = 16:05
Duration = tDurationCropped = 2:49
Distance = tMiles = 5.6
Average speed overall = tMph = 2.0

Track points = tTrackpoints = 452

Max altitude = tMaxAlt = 346
Gross ascent = tAsc = 430
Gross descent = tDesc = 430

FW main header = tFWHdr1 = Wednesday 23 June 2021: Circular walk with Janet, Ashurst
FW 2nd line = tFWHdr2 = Start 13:15, End 16:05,  Dur'n 2:49 , 5.6 miles, avg. mph 2.0
FW 3rd line = tFWHdr3 = Gross asc/desc 430 ft, Max 346 ft

FW map location = tFWlink = C:\Users\terry\Dropbox\FinishedWalks\20210623Ashurst-J-u452-m5.6.jpg
Elevation profile summary (PS) = tPSlink = C:\Users\terry\Dropbox\FinishedWalks\20210623Ashurst-J-u452-m5.6-PS.jpg
Photo example = tPhotoLink = C:\Users\terry\Dropbox\Camera Uploads\
Text source link = tSourceLink = C:\Users\terry\Dropbox\FinishedWalks\20210623Ashurst-J-u452-m5.6.txt
Report date = tReportDate = 24 June 2021
And finally here is what a successful result would look like:

Image
Last edited by terrypin on Thu Jun 24, 2021 10:20 pm, edited 1 time in total.
--
Terry, East Grinstead, UK
Using PSP 8 & PSP 2018 under Win 10
LeviFiction
Advisor
Posts: 6472
Joined: Thu Oct 02, 2008 1:07 pm
operating_system: Windows 10
System_Drive: C
32bit or 64bit: 64 Bit
motherboard: Alienware M17xR4
processor: Intel Core i7-3630QM CPU - 2_40GH
ram: 6 GB
Video Card: NVIDIA GeForce GTX 660M
sound_card: Sound Blaster Recon3Di
Hard_Drive_Capacity: 500GB
Corel programs: PSP: 8-2023
Location: USA

Re: Adapting this code from Levi?

Post by LeviFiction »

EDIT: Couldn't sleep so I finally got around to testing the code, there were two big-ish typos that I needed to fix and have done so. Also noticed that the coordinates were off by 1 each because the Line numbers and character numbers are all 0 indexed. So I just subtracted one from each and it worked perfectly.

The problem comes from your lack of understanding of programming. And that's my fault I should have given examples.

In Python, as with most all programming languages, strings (like filenames) must be surrounded by quotes "This is a string". You aren't doing that. Also because Python was made compatible with linux systems originally in Windows you have to escape the "\" character with another "\". So a path would be written like this "C:\\Users\\terry\\Dropbox\\FinishedWalks\\Source.txt" Remember quotes are important.

You also replaced the text "filename" with your path which is wrong. Filename is a parameter and variable, not a placeholder for you to change things when adding it to your script. I didn't explain this, and I apologize. Your hardcoded string is added when the function is called, not inside the function definition.

So here's how the code should look

Code: Select all

# ATTEMPT #1 TO CHANGE USING TEXT FILE
# ************************************
from JascApp import *

def ScriptProperties():
    return {
        'Author': u'Terry Pinnell',
        'Copyright': u'',
        'Description': u'',
        'Host': u'Paint Shop Pro',
        'Host Version': u'8.10'
        }

def Do(Environment):
    # EnableOptimizedScriptUndo
    App.Do( Environment, 'EnableOptimizedScriptUndo', {
           
            })
    # ASSUMES THAT VALUE OF MILES (%tMiles%) IS ON CLIPBOARD
    # ******************************************************
    
    # Text
    App.Do( Environment, 'Text', {
            'CreateAs': App.Constants.CreateAs.Vector,
            'Segments': [{
                'Bold': App.Constants.Boolean.true,
                'Fill': {
                    'Color': (0,0,0),
                    'Pattern': None,
                    'Gradient': None,
                    'Texture': None,
                    'Identity': u'Material'
                    },
                'Font': u'Arial',
                'LineStyle': {
                    'Name': u'',
                    'FirstCap': (u'Butt',0.25,0.25),
                    'LastCap': (u'Butt',0.25,0.25),
                    'FirstSegCap': (u'',0.25),
                    'LastSegCap': (u'',0.25),
                    'UseSegmentCaps': App.Constants.Boolean.false,
                    'Segments': []
                    },
                'LineWidth': 0,
                'PointSize': 36,
                'Start': (1460.5,314.5),
                'Stroke': {
                    'Color': None,
                    'Pattern': None,
                    'Gradient': None,
                    'Texture': None,
                    'Identity': u'Material'
                    }
                },{
                'Antialias': App.Constants.Boolean.true,
                'WarpText': App.Constants.Boolean.true,
                'AutoKern': App.Constants.Boolean.true,
                'Bold': App.Constants.Boolean.true,
                'Kerning': 0,
                'Leading': 0,
                'Fill': {
                    'Color': (0,0,0),
                    'Pattern': None,
                    'Gradient': None,
                    'Texture': None,
                    'Identity': u'Material'
                    },
                'Font': u'Arial',
                'Italic': App.Constants.Boolean.false,
                'Join': App.Constants.JointStyle.Miter,
                'LineStyle': {
                    'Name': u'',
                    'FirstCap': (u'Butt',0.25,0.25),
                    'LastCap': (u'Butt',0.25,0.25),
                    'FirstSegCap': (u'',0.25),
                    'LastSegCap': (u'',0.25),
                    'UseSegmentCaps': App.Constants.Boolean.false,
                    'Segments': []
                    },
                'LineWidth': 0, 
                'MiterLimit': 10,
                'PointSize': 36,     
                'SetText': App.Constants.Justify.Left,
                'Start': (1460.5,314.5),
                'Strikethru': App.Constants.Boolean.false,
                'Stroke': {
                    'Color': (255,255,255),
                    'Pattern': None,
                    'Gradient': None,
                    'Texture': None,
                    'Identity': u'Material'
                    },
                'Underline': App.Constants.Boolean.false
                },{
                'Characters': getText("C:\\Users\\terry\\Dropbox\\FinishedWalks\\Source.txt", 11, 20)  #You put the parameters inside the function call here which returns the text for the "Characters" parameter inside the Text function
                }],
            'SavedText': None,
            'FinalApply': App.Constants.Boolean.false,
            'Matrix': None,
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Default,
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            })
    # SelectNone
    App.Do( Environment, 'SelectNone', {
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Default, 
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            })


# NEW CODE
# --------
# filename = C:\Users\terry\Dropbox\FinishedWalks\Source.txt
# Its 12th line is
# Distance = tMiles = 5.6
# and '5.6' occupies the three character positions 21-23 (which are the last chars on the line)

def getText(filename, lineNum, offset):
    f = open(filename, 'r')
    lines = f.readlines()
    f.close()
    return lines[lineNum][offset:]  #Returns everything in the specific line after the characterindex to the end of the line
    
terrypin
Posts: 489
Joined: Tue Jun 29, 2010 9:51 am
operating_system: Windows 10
System_Drive: C
32bit or 64bit: 64 Bit
motherboard: Asus Z170 Pro 4
processor: Intel Core i7 6700K 4.0GHz
ram: 32 GB
Video Card: None - uses built-in graphics
sound_card: HD onboard sound card
Hard_Drive_Capacity: 4.256 TB
Monitor/Display Make & Model: iLyama Prolite E2403WS 24" 1920x1200
Corel programs: Paint Shop Pro 8; Paint Shop Pro 2018
Location: East Grinstead UK

Re: Adapting this code from Levi?

Post by terrypin »

Sorry for being slow to get this - and hope it didn't contribute to your insomnia! But I still get same error message.

Here is my latest code, but (apart from removing the two capitalised ASSUMPTION comments still in your version) I've changed only the last part. See my comments there.

Edit: One of the variations tried was to replace the variables in the return line, i.e:
return lines[11][20:]
Also, I recall we had trouble at one stage with tabs versus spaces. Clutching at straws here... ;-)

Could you post exactly what you have in your working code please, so that I can make a line by line comparison? I'll create any files and folders you used in your test.

Code: Select all

# ATTEMPT #3 TO CHANGE USING TEXT FILE
# ************************************
from JascApp import *

def ScriptProperties():
    return {
        'Author': u'Terry Pinnell',
        'Copyright': u'',
        'Description': u'',
        'Host': u'Paint Shop Pro',
        'Host Version': u'8.10'
        }

def Do(Environment):
    # EnableOptimizedScriptUndo
    App.Do( Environment, 'EnableOptimizedScriptUndo', {
           
            })
        
    # Text
    App.Do( Environment, 'Text', {
            'CreateAs': App.Constants.CreateAs.Vector,
            'Segments': [{
                'Bold': App.Constants.Boolean.true,
                'Fill': {
                    'Color': (0,0,0),
                    'Pattern': None,
                    'Gradient': None,
                    'Texture': None,
                    'Identity': u'Material'
                    },
                'Font': u'Arial',
                'LineStyle': {
                    'Name': u'',
                    'FirstCap': (u'Butt',0.25,0.25),
                    'LastCap': (u'Butt',0.25,0.25),
                    'FirstSegCap': (u'',0.25),
                    'LastSegCap': (u'',0.25),
                    'UseSegmentCaps': App.Constants.Boolean.false,
                    'Segments': []
                    },
                'LineWidth': 0,
                'PointSize': 36,
                'Start': (1460.5,314.5),
                'Stroke': {
                    'Color': None,
                    'Pattern': None,
                    'Gradient': None,
                    'Texture': None,
                    'Identity': u'Material'
                    }
                },{
                'Antialias': App.Constants.Boolean.true,
                'WarpText': App.Constants.Boolean.true,
                'AutoKern': App.Constants.Boolean.true,
                'Bold': App.Constants.Boolean.true,
                'Kerning': 0,
                'Leading': 0,
                'Fill': {
                    'Color': (0,0,0),
                    'Pattern': None,
                    'Gradient': None,
                    'Texture': None,
                    'Identity': u'Material'
                    },
                'Font': u'Arial',
                'Italic': App.Constants.Boolean.false,
                'Join': App.Constants.JointStyle.Miter,
                'LineStyle': {
                    'Name': u'',
                    'FirstCap': (u'Butt',0.25,0.25),
                    'LastCap': (u'Butt',0.25,0.25),
                    'FirstSegCap': (u'',0.25),
                    'LastSegCap': (u'',0.25),
                    'UseSegmentCaps': App.Constants.Boolean.false,
                    'Segments': []
                    },
                'LineWidth': 0, 
                'MiterLimit': 10,
                'PointSize': 36,     
                'SetText': App.Constants.Justify.Left,
                'Start': (1460.5,314.5),
                'Strikethru': App.Constants.Boolean.false,
                'Stroke': {
                    'Color': (255,255,255),
                    'Pattern': None,
                    'Gradient': None,
                    'Texture': None,
                    'Identity': u'Material'
                    },
                'Underline': App.Constants.Boolean.false
                },{
                'Characters': getText("C:\\Users\\terry\\Dropbox\\FinishedWalks\\Source.txt", 11, 20)  #You put the parameters inside the function call here which returns the text for the "Characters" parameter inside the Text function
                }],
            'SavedText': None,
            'FinalApply': App.Constants.Boolean.false,
            'Matrix': None,
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Default,
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            })
    # SelectNone
    App.Do( Environment, 'SelectNone', {
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Default, 
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            })


# NEW CODE
# --------
# filename = "C:\\Users\\terry\\Dropbox\\FinishedWalks\\Source.txt"
# I assume I use that to replace your 'filename'? But only in the 'def' line?
# The 12th line of Source.txt is
# Distance = tMiles = 5.6
# So I assume I replace your 'lineNum' with 11 (not 12)? But only in the 'def' line?
# And '5.6' occupies the three character positions 21-23 (which are the last chars on the line)
# So I assume your 'offset' = 20 ? (You called it 'characterindex' before?)
# But still fails with message as before, implicating line 124
# I also tried adding a line 'r = Tk()', as in your old scripts for PSP 8, but got same error.

def getText("C:\\Users\\terry\\Dropbox\\FinishedWalks\\Source.txt", 11, 20):
    f = open(filename, 'r')
    lines = f.readlines()
    f.close()
    return lines[lineNum][offset:]  #Returns everything in the specific line after the characterindex to the 
    end of the line
    
 
--
Terry, East Grinstead, UK
Using PSP 8 & PSP 2018 under Win 10
LeviFiction
Advisor
Posts: 6472
Joined: Thu Oct 02, 2008 1:07 pm
operating_system: Windows 10
System_Drive: C
32bit or 64bit: 64 Bit
motherboard: Alienware M17xR4
processor: Intel Core i7-3630QM CPU - 2_40GH
ram: 6 GB
Video Card: NVIDIA GeForce GTX 660M
sound_card: Sound Blaster Recon3Di
Hard_Drive_Capacity: 500GB
Corel programs: PSP: 8-2023
Location: USA

Re: Adapting this code from Levi?

Post by LeviFiction »

In my reply I gave you the final working code you didn't need to edit. Again you committed the same problem as last time. You're replacing the variable 'Filename" in the function declaration. I don't know if I can explain this properly. But I shall try.

Code: Select all

def getText(filename, lineNum, offset):
That line of code above is called the "function declaration" it tells Python what the name of the function is, and what the names of the variables that will hold your parameters are called. This will never get edited by you with hardcoded information. You do not need to replace "filename" or "lineNum" or "offset" with hardcoded data. It won't work. PSP is expecting variable names here, not data. These variables then get used inside the function. So where I have "f = open(filename, 'r')" PSP won't know what "filename" is because you've removed the variable from the declaration.

Your information will get added where we "Call" the function. And we do this inside of the Text command. It's specifically this line of the program

Code: Select all

                'Characters': getText("C:\\Users\\terry\\Dropbox\\FinishedWalks\\Source.txt", 11, 20)  #You put the parameters inside the function call here which returns the text for the "Characters" parameter inside the Text function
Here you can see we have "getText()" but there is no "def" keyword in front of it. This is not a function declaration. This is us calling the function, and we are passing in the hardcoded data, the file path and the numbers. These will get sent to the function and placed into those variables "filename", "lineNum", and "offset" for you. So you never have to touch the declaration portion.

So go back, grab the code i posted, and it should just work. You don't need to do anything.
terrypin
Posts: 489
Joined: Tue Jun 29, 2010 9:51 am
operating_system: Windows 10
System_Drive: C
32bit or 64bit: 64 Bit
motherboard: Asus Z170 Pro 4
processor: Intel Core i7 6700K 4.0GHz
ram: 32 GB
Video Card: None - uses built-in graphics
sound_card: HD onboard sound card
Hard_Drive_Capacity: 4.256 TB
Monitor/Display Make & Model: iLyama Prolite E2403WS 24" 1920x1200
Corel programs: Paint Shop Pro 8; Paint Shop Pro 2018
Location: East Grinstead UK

Re: Adapting this code from Levi?

Post by terrypin »

Got it, many thanks!

I had remained completely unaware until now that you had defined the variables earlier in the script in line 95, thus:
'Characters': getText("C:\\Users\\terry\\Dropbox\\FinishedWalks\\Source.txt", 11, 20)

Hence my final note last night: "I've changed only the end section, apart from comments." Clearly I should have SEEN that line, but instead I therefore wrongly assumed that the variable values had to be entered in that last section, and proceeded to do so, screwing it up!

One tiny flaw is that the text is getting an additional spurious character:

Image


Thanks so much for your patience!
--
Terry, East Grinstead, UK
Using PSP 8 & PSP 2018 under Win 10
terrypin
Posts: 489
Joined: Tue Jun 29, 2010 9:51 am
operating_system: Windows 10
System_Drive: C
32bit or 64bit: 64 Bit
motherboard: Asus Z170 Pro 4
processor: Intel Core i7 6700K 4.0GHz
ram: 32 GB
Video Card: None - uses built-in graphics
sound_card: HD onboard sound card
Hard_Drive_Capacity: 4.256 TB
Monitor/Display Make & Model: iLyama Prolite E2403WS 24" 1920x1200
Corel programs: Paint Shop Pro 8; Paint Shop Pro 2018
Location: East Grinstead UK

Re: Adapting this code from Levi?

Post by terrypin »

Levi:
It seems that an unwanted EOL or 'Return' character has been pasted. If I edit the text and delete the invisible character at its end, it disappears.
It's the same for the several other similar scripts I've now made by trivial editing of your 'Miles' script.

I sometimes get the same issue when i'm writing macros with Macro Express Pro for working with Excel cell contents. The program has a 'Trim' facilty to strip such spurious stuff from variables, so I'm wondering if Python has an equivalent please?

Image
--
Terry, East Grinstead, UK
Using PSP 8 & PSP 2018 under Win 10
LeviFiction
Advisor
Posts: 6472
Joined: Thu Oct 02, 2008 1:07 pm
operating_system: Windows 10
System_Drive: C
32bit or 64bit: 64 Bit
motherboard: Alienware M17xR4
processor: Intel Core i7-3630QM CPU - 2_40GH
ram: 6 GB
Video Card: NVIDIA GeForce GTX 660M
sound_card: Sound Blaster Recon3Di
Hard_Drive_Capacity: 500GB
Corel programs: PSP: 8-2023
Location: USA

Re: Adapting this code from Levi?

Post by LeviFiction »

Python has strip()

I have now added it to the return value of the getText() function. Here's the new getText

Code: Select all

def getText(filename, lineNum, offset):
    f = open(filename, 'r')
    lines = f.readlines()
    f.close()
    return lines[lineNum][offset:].strip()
terrypin
Posts: 489
Joined: Tue Jun 29, 2010 9:51 am
operating_system: Windows 10
System_Drive: C
32bit or 64bit: 64 Bit
motherboard: Asus Z170 Pro 4
processor: Intel Core i7 6700K 4.0GHz
ram: 32 GB
Video Card: None - uses built-in graphics
sound_card: HD onboard sound card
Hard_Drive_Capacity: 4.256 TB
Monitor/Display Make & Model: iLyama Prolite E2403WS 24" 1920x1200
Corel programs: Paint Shop Pro 8; Paint Shop Pro 2018
Location: East Grinstead UK

Re: Adapting this code from Levi?

Post by terrypin »

Excellent, thanks a lot Levi, that now works perfectly!

Terry
--
Terry, East Grinstead, UK
Using PSP 8 & PSP 2018 under Win 10