Page 1 of 1

Find Terms with Line Numbers

Posted: 2015-12-15 11:25:29
by jb
I’ve got several documents, each with about 1000 lines (poetry). I also have a list of about 25 words I’m interested in finding and listing with corresponding line numbers. I do know how to find those words, and for the time being I’ve styled them (Bold) so that they stand out to the eye.

But I'd like a list of each found word with the line numbers where it appears. Like so:

apple: 23, 77, 758
orange: 326, 445
pear: 89, 976

Any help appreciated.
Thanks
James

Re: Find Terms with Line Numbers

Posted: 2015-12-15 22:08:51
by phspaelti
Hello James,

I'm assuming that by line numbers you mean the line numbers provided by Nisus. Here is some code that will do that. To run this code, put the find expression in the find dialog, and then run the macro:

Code: Select all

# Find with Line Numbers
$doc = Document.active

# Get the find expression from the Find dialog and collect the search hits
$findExp = Read Find Expression
$finds = $doc.text.findAll $findExp, '*', '-am'

# Loop through all the search hits
$results = Array.new
foreach $find in $finds
    # Combine each hit with the line number
    $results.push $find.substring & ': ' & $find.text.lineNumberAtIndex($find.location)
end

# Sort the results
$results.sort

# Output the results in a new document
Document.newWithText $results.join("\n")
Find with Line Numbers.nwm
(3.92 KiB) Downloaded 65 times
Now this macro is very 'bare bones' and will put each word on a separate line followed by the line number, which means it will give:
apple: 23
apple: 77
apple: 758
orange: 326
orange: 445

You can of course just use Find/Replace to reshape this to the output you want.
To do it directly, the above code could be changed as follows:
  • Change the results array to a hash with the found words as keys, and the values being arrays of line numbers
  • While looping add the line numbers to the hash value array that has the word as key
  • Add another loop, which goes through the word/keys in order and combines each array of line numbers to a comma list
Here the macro with those changes:
Find with Line Numbers (comma list).nwm
(4.03 KiB) Downloaded 61 times

Re: Find Terms with Line Numbers

Posted: 2015-12-16 05:20:42
by jb
Thank you, Philip.
This is perfect, and of course the second macro is what I really want. So an extra Thank You for that.

I keep telling myself that one day I will study some of the macros you've made (for me) and learn to make them myself, but it seems that there is always just enough mysterious magic that I stumble. I will try again ;-)

Thanks much,
James