Search & replace from csv list

Can someone point me to what must be an obvious problem I am over looking with this script.

I set out to write an AppleScript fusing textedit that performs a series of search and replaces on selected text using the csv file /Users/jeff/Documents/COMMON FILES/CND-USA Spelling List.csv as the source and replacemnt items.

The idea is to replace American Spellings wither Canadian spelling equivalents, with American words in column a and Canadian terms in column b.
– Get the path to the CSV file
set csvPath to “/Users/jeff/Documents/COMMON FILES/CND-USA Spelling List.csv”

-- Read the CSV file into a list of search and replacement patterns
set searchAndReplacements to {}
set csvFile to (open for access csvPath)
set csvData to (read csvFile using delimiter ",")
close access csvFile

repeat with row in csvData
	set searchPattern to "\\b" & item 1 of row & "\\b"
	set replacementPattern to item 2 of row
	set end of searchAndReplacements to {searchPattern, replacementPattern}
end repeat

-- Get the selected text in TextEdit
tell application "TextEdit"
	activate
	set selectedText to the text of the front document
end tell

-- Perform the search and replaces on whole words only
repeat with searchAndReplacement in searchAndReplacements
	set searchPattern to item 1 of searchAndReplacement
	set replacementPattern to item 2 of searchAndReplacement
	set selectedText to my replaceString(selectedText, searchPattern, replacementPattern)
end repeat

-- Replace the selected text with the modified text
tell application "TextEdit"
	set the text of the front document to selectedText
end tell

on replaceString(sourceString, searchString, replaceString)
	set {oldTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, searchString}
	set stringList to text items of sourceString
	set AppleScript's text item delimiters to replaceString
	set newString to stringList as text
	set AppleScript's text item delimiters to oldTID
	return newString
end replaceString

It would be nice if you’d enclose your code in three backticks like so
```
code goes here
```
That would give it highlighting, make it easily recognisable as code and simple to copy.
And maybe explaining what does and what does not work…
(It seems that you mix up regular expression into this, which will not work, I guess)

1 Like

Thanks for the tip. hope it looks better now

It does. But \\b does not make sense in a regular search as you can do with AS. Those are metacharacters for regular expression search, to limit the search to word boundaries. If I were to write this stuff, I’d do it in JS (using regular expressions) like so:

(() => {
  const csvPath = "/Users/jeff/Documents/COMMON FILES/CND-USA Spelling List.csv";
  const ca = Application.currentApplication();
  ca.includeStandardAdditions = true;
  const csvData= ca.readFile(Path(csvPath), { usingDelimiter: '\n'}); /* csvData is an array of lines from the file */

  const app = Application("TextEdit");
  let txt =  app.documents[0].text(); /* Gets the text of the first document */

  /* Loop over all replacement patterns */
  csvData.forEach(line => {
    const fields = line.split(','); /* Split the current line at comma into two fields */
    const search = new RegExp(`\b${fields[0]}\b`,'g'); /* RE with word boundaries */
    const replace = fields[1];
   /* Do the replacement for the current pattern */
    txt = txt.replaceAll(search, replace);
  })
})()

Note I did not test this code, it might well contain errors and is meant only for illustration.

You can do a full RegEx search/replace easily enough with AppleScriptObjC:

--------------------------------------------------------
# Auth: Christopher Stone <scriptmeister@thestoneforge.com>
# dCre: 2016/05/08 00:59
# dMod: 2021/08/27 19:51
# Appl: AppleScriptObjC
# Task: Find-Replace or Change-Text Handler
# Libs: None
# Osax: None
# Tags: @Applescript, @Script, @ASObjC, @Find, @Replace, @Text, @RegEx, @cngStr, @Change
--------------------------------------------------------
use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
--------------------------------------------------------

set dataString to "
one, two
two
three
"

set newStr to its cngStr:"\\btwo\\b" intoString:"2" inString:dataString

--------------------------------------------------------
--» HANDLERS
--------------------------------------------------------
on cngStr:findString intoString:replaceString inString:dataString
   set anNSString to current application's NSString's stringWithString:dataString
   set dataString to (anNSString's ¬
      stringByReplacingOccurrencesOfString:findString withString:replaceString ¬
         options:(current application's NSRegularExpressionSearch) range:{0, length of dataString}) as text
end cngStr:intoString:inString:
--------------------------------------------------------
1 Like