Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #9680 > unrolled thread

a little parsing challenge ☺

Started byXah Lee <xahlee@gmail.com>
First post2011-07-17 00:47 -0700
Last post2011-07-19 22:43 -0700
Articles 20 on this page of 72 — 28 participants

Back to article view | Back to comp.lang.python


Contents

  a little parsing challenge ☺ Xah Lee <xahlee@gmail.com> - 2011-07-17 00:47 -0700
    Re: a little parsing challenge ☺ Raymond Hettinger <python@rcn.com> - 2011-07-17 02:48 -0700
      Re: a little parsing challenge ☺ Robert Klemme <shortcutter@googlemail.com> - 2011-07-17 15:20 +0200
        Re: a little parsing challenge ☺ mhenn <michihenn@hotmail.com> - 2011-07-17 15:55 +0200
          Re: a little parsing challenge ☺ Robert Klemme <shortcutter@googlemail.com> - 2011-07-17 18:01 +0200
            Re: a little parsing challenge ☺ Robert Klemme <shortcutter@googlemail.com> - 2011-07-17 18:54 +0200
      Re: a little parsing challenge ☺ Thomas Boell <tboell@domain.invalid> - 2011-07-17 17:49 +0200
        Re: a little parsing challenge ☺ Raymond Hettinger <python@rcn.com> - 2011-07-17 12:16 -0700
      Re: a little parsing challenge ☺ Xah Lee <xahlee@gmail.com> - 2011-07-18 07:39 -0700
        Re: a little parsing challenge ☺ Robert Klemme <shortcutter@googlemail.com> - 2011-07-20 08:23 +0200
        Re: a little parsing challenge ☺ Xah Lee <xahlee@gmail.com> - 2011-07-20 03:31 -0700
          Re: a little parsing challenge ☺ "Uri Guttman" <uri@StemSystems.com> - 2011-07-20 12:31 -0400
            Re: a little parsing challenge ☺ rusi <rustompmody@gmail.com> - 2011-07-20 10:30 -0700
            Re: a little parsing challenge ☺ merlyn@stonehenge.com (Randal L. Schwartz) - 2011-07-20 12:06 -0700
              Re: a little parsing challenge ☺ Jason Earl <jearl@notengoamigos.org> - 2011-07-20 14:57 -0600
      Re: a little parsing challenge ☺ Xah Lee <xahlee@gmail.com> - 2011-07-19 09:54 -0700
        Re: a little parsing challenge ☺ Thomas Jollans <t@jollybox.de> - 2011-07-19 20:07 +0200
          Re: a little parsing challenge ☺ Xah Lee <xahlee@gmail.com> - 2011-07-21 05:58 -0700
            Re: a little parsing challenge ☺ Ian Kelly <ian.g.kelly@gmail.com> - 2011-07-21 08:26 -0600
              Re: a little parsing challenge ☺ Xah Lee <xahlee@gmail.com> - 2011-07-21 08:36 -0700
                Re: a little parsing challenge ☺ python@bdurham.com - 2011-07-21 12:43 -0400
                  Re: a little parsing challenge ☺ Xah Lee <xahlee@gmail.com> - 2011-07-21 11:53 -0700
                    Re: a little parsing challenge ☺ Terry Reedy <tjreedy@udel.edu> - 2011-07-21 18:37 -0400
            Re: a little parsing challenge ☺ John O'Hagan <research@johnohagan.com> - 2011-07-25 15:57 +1000
        Re: a little parsing challenge ☺ Ian Kelly <ian.g.kelly@gmail.com> - 2011-07-19 12:08 -0600
    Re: a little parsing challenge ☺ Chris Angelico <rosuav@gmail.com> - 2011-07-17 21:34 +1000
      Re: a little parsing challenge ☺ rusi <rustompmody@gmail.com> - 2011-07-17 04:52 -0700
      Re: a little parsing challenge ☺ Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2011-07-17 16:15 +0200
        Re: a little parsing challenge ☺ Raymond Hettinger <python@rcn.com> - 2011-07-17 12:18 -0700
          Re: a little parsing challenge ☺ Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2011-07-17 22:16 +0200
            Re: a little parsing challenge ☺ Thomas Jollans <t@jollybox.de> - 2011-07-17 22:57 +0200
        Re: a little parsing challenge ☺ Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2011-07-17 23:43 +0200
        Re: a little parsing challenge ☺ Rouslan Korneychuk <rouslank@msn.com> - 2011-07-18 03:09 -0400
          Re: a little parsing challenge ☺ Stefan Behnel <stefan_ml@behnel.de> - 2011-07-18 09:24 +0200
            Re: a little parsing challenge ☺ Rouslan Korneychuk <rouslank@msn.com> - 2011-07-18 04:04 -0400
          Re: a little parsing challenge ☺ Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2011-07-18 18:46 +0200
            Re: a little parsing challenge ☺ Rouslan Korneychuk <rouslank@msn.com> - 2011-07-18 14:14 -0400
          Re: a little parsing challenge ☺ Xah Lee <xahlee@gmail.com> - 2011-07-21 06:23 -0700
            Re: a little parsing challenge ☺ Rouslan Korneychuk <rouslank@msn.com> - 2011-07-21 17:54 -0400
    Re: a little parsing challenge ☺ gene heskett <gheskett@wdtv.com> - 2011-07-17 10:26 -0400
    Re: a little parsing challenge ☺ Thomas Jollans <t@jollybox.de> - 2011-07-17 08:31 -0700
      Re: a little parsing challenge ☺ Xah Lee <xahlee@gmail.com> - 2011-07-19 10:49 -0700
        Re: a little parsing challenge ☺ Thomas Jollans <t@jollybox.de> - 2011-07-19 20:14 +0200
          Re: a little parsing challenge ☺ Xah Lee <xahlee@gmail.com> - 2011-07-21 05:29 -0700
            Re: a little parsing challenge ☺ Thomas Jollans <t@jollybox.de> - 2011-07-21 15:21 +0200
        Re: a little parsing challenge ☺ Thomas Jollans <t@jollybox.de> - 2011-07-19 20:17 +0200
    Re: a little parsing challenge ☺ rantingrick <rantingrick@gmail.com> - 2011-07-17 18:52 -0700
    Re: a little parsing challenge ☺ Billy Mays <81282ed9a88799d21e77957df2d84bd6514d9af6@myhashismyemail.com> - 2011-07-18 13:12 -0400
      Re: a little parsing challenge ☺ Ian Kelly <ian.g.kelly@gmail.com> - 2011-07-18 12:10 -0600
        Re: a little parsing challenge ☺ Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2011-07-18 23:59 +0200
          Re: a little parsing challenge ☺ Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2011-07-19 08:09 +0200
          Re: a little parsing challenge ☺ Xah Lee <xahlee@gmail.com> - 2011-07-19 10:32 -0700
      Re: a little parsing challenge ☺ Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-07-19 09:56 +1000
        Re: a little parsing challenge ☺ Billy Mays <noway@nohow.com> - 2011-07-18 22:07 -0400
          Re: a little parsing challenge ☺ rusi <rustompmody@gmail.com> - 2011-07-18 19:50 -0700
            Re: a little parsing challenge ☺ Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-07-19 13:11 +1000
              Re: a little parsing challenge ☺ rusi <rustompmody@gmail.com> - 2011-07-18 21:59 -0700
                Re: a little parsing challenge ☺ Chris Angelico <rosuav@gmail.com> - 2011-07-19 15:36 +1000
          Re: a little parsing challenge ☺ MRAB <python@mrabarnett.plus.com> - 2011-07-19 04:08 +0100
          Re: a little parsing challenge ☺ Benjamin Kaplan <benjamin.kaplan@case.edu> - 2011-07-18 20:54 -0700
          Re: a little parsing challenge ☺ Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-07-19 14:30 +1000
          Re: a little parsing challenge ☺ Xah Lee <xahlee@gmail.com> - 2011-07-19 01:58 -0700
      Re: a little parsing challenge ☺ Xah Lee <xahlee@gmail.com> - 2011-07-19 10:14 -0700
        Re: a little parsing challenge ☺ Billy Mays <81282ed9a88799d21e77957df2d84bd6514d9af6@myhashismyemail.com> - 2011-07-19 13:33 -0400
          Re: a little parsing challenge ☺ Xah Lee <xahlee@gmail.com> - 2011-07-19 11:12 -0700
            Re: a little parsing challenge ☺ Terry Reedy <tjreedy@udel.edu> - 2011-07-19 15:09 -0400
              Re: a little parsing challenge ☺ jmfauth <wxjmfauth@gmail.com> - 2011-07-19 23:29 -0700
                Re: a little parsing challenge ☺ Ian Kelly <ian.g.kelly@gmail.com> - 2011-07-20 01:29 -0600
                  Re: a little parsing challenge ☺ jmfauth <wxjmfauth@gmail.com> - 2011-07-20 00:54 -0700
                    Re: a little parsing challenge ☺ Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-07-20 18:18 +1000
    Re: a little parsing challenge ? sln@netherlands.com - 2011-07-18 12:34 -0700
    Re: a little parsing challenge ☺ Mark Tarver <dr.mtarver@gmail.com> - 2011-07-19 22:43 -0700

Page 1 of 4  [1] 2 3 4  Next page →


#9680 — a little parsing challenge ☺

FromXah Lee <xahlee@gmail.com>
Date2011-07-17 00:47 -0700
Subjecta little parsing challenge ☺
Message-ID<36037253-086b-4467-a1db-9492d3772e78@r5g2000prf.googlegroups.com>
2011-07-16

folks, this one will be interesting one.

the problem is to write a script that can check a dir of text files
(and all subdirs) and reports if a file has any mismatched matching
brackets.

• The files will be utf-8 encoded (unix style line ending).

• If a file has mismatched matching-pairs, the script will display the
file name, and the  line number and column number of the first
instance where a mismatched bracket occures. (or, just the char number
instead (as in emacs's “point”))

• the matching pairs are all single unicode chars. They are these and
nothing else: () {} [] “” ‹› «» 【】 〈〉 《》 「」 『』
Note that ‘single curly quote’ is not consider matching pair here.

• You script must be standalone. Must not be using some parser tools.
But can call lib that's part of standard distribution in your lang.

Here's a example of mismatched bracket: ([)], (“[[”), ((, 】etc. (and
yes, the brackets may be nested. There are usually text between these
chars.)

I'll be writing a emacs lisp solution and post in 2 days. Ι welcome
other lang implementations. In particular, perl, python, php, ruby,
tcl, lua, Haskell, Ocaml. I'll also be able to eval common lisp
(clisp) and Scheme lisp (scsh), Java. Other lang such as Clojure,
Scala, C, C++, or any others, are all welcome, but i won't be able to
eval it. javascript implementation will be very interesting too, but
please indicate which and where to install the command line version.

I hope you'll find this a interesting “challenge”. This is a parsing
problem. I haven't studied parsers except some Wikipedia reading, so
my solution will probably be naive. I hope to see and learn from your
solution too.

i hope you'll participate. Just post solution here. Thanks.

 Xah

[toc] | [next] | [standalone]


#9688

FromRaymond Hettinger <python@rcn.com>
Date2011-07-17 02:48 -0700
Message-ID<99245842-e205-4a34-8f9d-c64d41e044b6@j9g2000prj.googlegroups.com>
In reply to#9680
On Jul 17, 12:47 am, Xah Lee <xah...@gmail.com> wrote:
> i hope you'll participate. Just post solution here. Thanks.

http://pastebin.com/7hU20NNL


Raymond

[toc] | [prev] | [next] | [standalone]


#9703

FromRobert Klemme <shortcutter@googlemail.com>
Date2011-07-17 15:20 +0200
Message-ID<98g5spFcm4U1@mid.individual.net>
In reply to#9688
On 07/17/2011 11:48 AM, Raymond Hettinger wrote:
> On Jul 17, 12:47 am, Xah Lee<xah...@gmail.com>  wrote:
>> i hope you'll participate. Just post solution here. Thanks.
>
> http://pastebin.com/7hU20NNL

Ruby solution: https://gist.github.com/1087583

Kind regards

robert

[toc] | [prev] | [next] | [standalone]


#9704

Frommhenn <michihenn@hotmail.com>
Date2011-07-17 15:55 +0200
Message-ID<4e22e9cd$0$6574$3ca0ca56@newsspool3.vodafone-ip.de>
In reply to#9703
Am 17.07.2011 15:20, schrieb Robert Klemme:
> On 07/17/2011 11:48 AM, Raymond Hettinger wrote:
>> On Jul 17, 12:47 am, Xah Lee<xah...@gmail.com>  wrote:
>>> i hope you'll participate. Just post solution here. Thanks.
>>
>> http://pastebin.com/7hU20NNL
> 
> Ruby solution: https://gist.github.com/1087583

I acutally don't know Ruby that well, but it looks like your program
recognizes "[(])" as correct although it is not, because you translate
"[(])" to "(())" (which is indeed correct, but does not resemble the
input correctly anymore).

> 
> Kind regards
> 
> robert

[toc] | [prev] | [next] | [standalone]


#9714

FromRobert Klemme <shortcutter@googlemail.com>
Date2011-07-17 18:01 +0200
Message-ID<98gfasFjq2U1@mid.individual.net>
In reply to#9704
On 07/17/2011 03:55 PM, mhenn wrote:
> Am 17.07.2011 15:20, schrieb Robert Klemme:
>> On 07/17/2011 11:48 AM, Raymond Hettinger wrote:
>>> On Jul 17, 12:47 am, Xah Lee<xah...@gmail.com>   wrote:
>>>> i hope you'll participate. Just post solution here. Thanks.
>>>
>>> http://pastebin.com/7hU20NNL
>>
>> Ruby solution: https://gist.github.com/1087583
>
> I acutally don't know Ruby that well, but it looks like your program
> recognizes "[(])" as correct although it is not, because you translate
> "[(])" to "(())" (which is indeed correct, but does not resemble the
> input correctly anymore).

Right you are.  The optimization breaks the logic.  Good catch!

Kind regards

	robert

[toc] | [prev] | [next] | [standalone]


#9721

FromRobert Klemme <shortcutter@googlemail.com>
Date2011-07-17 18:54 +0200
Message-ID<98gif3Fci0U1@mid.individual.net>
In reply to#9714
On 07/17/2011 06:01 PM, Robert Klemme wrote:
> On 07/17/2011 03:55 PM, mhenn wrote:
>> Am 17.07.2011 15:20, schrieb Robert Klemme:
>>> On 07/17/2011 11:48 AM, Raymond Hettinger wrote:
>>>> On Jul 17, 12:47 am, Xah Lee<xah...@gmail.com> wrote:
>>>>> i hope you'll participate. Just post solution here. Thanks.
>>>>
>>>> http://pastebin.com/7hU20NNL
>>>
>>> Ruby solution: https://gist.github.com/1087583
>>
>> I acutally don't know Ruby that well, but it looks like your program
>> recognizes "[(])" as correct although it is not, because you translate
>> "[(])" to "(())" (which is indeed correct, but does not resemble the
>> input correctly anymore).
>
> Right you are. The optimization breaks the logic. Good catch!

Turns out with a little possessiveness I can fix my original approach 
which has the added benefit of not needing three passes through the file 
(the two #tr's are obsolete now).

https://gist.github.com/1087583

Cheers

	robert

[toc] | [prev] | [next] | [standalone]


#9713

FromThomas Boell <tboell@domain.invalid>
Date2011-07-17 17:49 +0200
Message-ID<20110717174911.6f00792f@arcadia>
In reply to#9688
On Sun, 17 Jul 2011 02:48:42 -0700 (PDT)
Raymond Hettinger <python@rcn.com> wrote:

> On Jul 17, 12:47 am, Xah Lee <xah...@gmail.com> wrote:
> > i hope you'll participate. Just post solution here. Thanks.
> 
> http://pastebin.com/7hU20NNL

I'm new to Python. I think I'd have done it in a similar way (in any
language). Your use of openers/closers looks nice though. In the
initialization of openers, I guess you implicitly create a kind of
hash, right? Then the 'in' operator checks for the keys. That is elegant
because you have the openers and closers right next to each other, not
in separate lists.

But why do you enumerate with start=1? Shouldn't you start with index 0?

[toc] | [prev] | [next] | [standalone]


#9746

FromRaymond Hettinger <python@rcn.com>
Date2011-07-17 12:16 -0700
Message-ID<42a76bcc-c5e7-424e-9373-1ecd8f80df25@y13g2000prb.googlegroups.com>
In reply to#9713
On Jul 17, 8:49 am, Thomas Boell <tbo...@domain.invalid> wrote:
> But why do you enumerate with start=1? Shouldn't you start with index 0?

The problem specification says that the the char number should match
the emacs goto-char function which is indexed from one, not from
zero.  This is testable by taking the output of the program and
running it through emacs to see that the cursor gets moved exactly to
the location of the mismatched delimiter.


Raymond

[toc] | [prev] | [next] | [standalone]


#9806

FromXah Lee <xahlee@gmail.com>
Date2011-07-18 07:39 -0700
Message-ID<87f46fe8-5d1d-4ed0-b6e3-87c5f9262c38@t38g2000prj.googlegroups.com>
In reply to#9688
On Jul 17, 12:47 am, Xah Lee <xah...@gmail.com> wrote:
> 2011-07-16
>
> folks, this one will be interesting one.
>
> the problem is to write a script that can check a dir of text files
> (and all subdirs) and reports if a file has any mismatched matching
> brackets.
> …

Ok, here's my solution (pasted at bottom). I haven't tried to make it
elegant or terse, yet, seeing that many are already much elegent than
i could possibly do so with my code.

my solution basically use a stack. (i think all of us are doing
similar) Here's the steps:

• Go thru the file char by char, find a bracket char.
• check if the one on stack is a matching opening char. If so remove
it. Else, push the current onto the stack.
• Repeat the above till end of file.
• If the stack is not empty, then the file got mismatched brackets.
Report it.
• Do the above on all files.

Many elegant solutions. Raymond Hettinger is very quick, posted a
solution only after a hour or so when i posted it. Many others are
very short, very nice. Thank you all for writing them. I haven't
studied them yet. I'll run them all and post a summary in 2 days. (i
have few thousands files to run this test thru, many of them have
mismatched brackets. So i have good data to test with.)

PS we still lack a perl, Scheme lisp, tcl, lua versions. These
wouldn't be hard and would be interesting to read.  If you are picking
up one of these lang, this would be a good exercise.  Haskell too. I
particularly would like to see a javascript version ran from command
line. Maybe somebody can put this exercise to Google folks ... they
are like the js gods.

also, now that we have these home-brewed code, how'd a parser expert
do it? Is it possible to make it even simpler by using some parser
tools? (have no idea what those lex yacc do, or modern incarnations)
I've also been thinking whether this can be done with Parsing
Expression Grammar. That would make the code semantics really elegant
(as opposed home-cooked stack logic).

 Xah

;; -*- coding: utf-8 -*-
;; 2011-07-15, Xah Lee
;; go thru a file, check if all brackets are properly matched.
;; e.g. good: (…{…}… “…”…)
;; bad: ( [)]
;; bad: ( ( )

(setq inputDir "~/web/xahlee_org/p/") ; must end in slash

(defvar matchPairs '() "a alist. For each air, the car is opening
char, cdr is closing char.")

(setq matchPairs '(
                   ("(" . ")")
                   ("{" . "}")
                   ("[" . "]")
                   ("“" . "”")
                   ("‹" . "›")
                   ("«" . "»")
                   ("【" . "】")
                   ("〈" . "〉")
                   ("《" . "》")
                   ("「" . "」")
                   ("『" . "』")
                   )
      )

(defvar searchRegex "" "regex string of all pairs to search.")
(setq searchRegex "")
(mapc
 (lambda (mypair) ""
   (setq searchRegex (concat searchRegex (regexp-quote (car mypair))
"|" (regexp-quote (cdr mypair)) "|") )
   )
 matchPairs)

(setq searchRegex (replace-regexp-in-string "|$" "" searchRegex t
t)) ; remove the ending “|”

(setq searchRegex (replace-regexp-in-string "|" "\\|" searchRegex t
t)) ; change | to \\| for regex “or” operation

(defun my-process-file (fpath)
  "process the file at fullpath fpath ..."
  (let (myBuffer (ii 0) myStack ξchar ξpos)

    (setq myStack '() ) ; each element is a vector [char position]
    (setq ξchar "")

    (setq myBuffer (get-buffer-create " myTemp"))
    (set-buffer myBuffer)
    (insert-file-contents fpath nil nil nil t)

    (goto-char 1)
    (while (search-forward-regexp searchRegex nil t)
      (setq ξpos (point)  )
      (setq ξchar (buffer-substring-no-properties ξpos (- ξpos 1))  )

      ;; (princ (format "-----------------------------\nfound char: %s
\n" ξchar) )

      (let ((isClosingCharQ nil) (matchedOpeningChar nil) )
        (setq isClosingCharQ (rassoc ξchar matchPairs))
        (when isClosingCharQ (setq matchedOpeningChar (car
isClosingCharQ) ) )

        ;; (princ (format "isClosingCharQ is: %s\n" isClosingCharQ) )
        ;; (princ (format "matchedOpeningChar is: %s\n"
matchedOpeningChar) )

        (if
            (and
             (car myStack) ; not empty
             (equal (elt (car myStack) 0) matchedOpeningChar )
             )
            (progn
              ;; (princ (format "matched this bottom item on stack: %s
\n" (car myStack)) )
              (setq myStack (cdr myStack) )
              )
          (progn
            ;; (princ (format "did not match this bottom item on
stack: %s\n" (car myStack)) )
            (setq myStack (cons (vector ξchar ξpos) myStack) ) )
          )
        )
      ;; (princ "current stack: " )
      ;; (princ myStack )
      ;; (terpri )
      )

    (when (not (equal myStack nil))
      (princ "Error file: ")
      (princ fpath)
      (print (car myStack) )
      )
    (kill-buffer myBuffer)
    ))


;; (require 'find-lisp)

(let (outputBuffer)
  (setq outputBuffer "*xah match pair output*" )
  (with-output-to-temp-buffer outputBuffer
    (mapc 'my-process-file (find-lisp-find-files inputDir "\\.html$"))
    (princ "Done deal!")
    )
  )

[toc] | [prev] | [next] | [standalone]


#9939

FromRobert Klemme <shortcutter@googlemail.com>
Date2011-07-20 08:23 +0200
Message-ID<98naiiFlf4U1@mid.individual.net>
In reply to#9806
On 18.07.2011 16:39, Xah Lee wrote:
>
> On Jul 17, 12:47 am, Xah Lee<xah...@gmail.com>  wrote:
>> 2011-07-16
>>
>> folks, this one will be interesting one.
>>
>> the problem is to write a script that can check a dir of text files
>> (and all subdirs) and reports if a file has any mismatched matching
>> brackets.
>> …
>
> Ok, here's my solution (pasted at bottom). I haven't tried to make it
> elegant or terse, yet, seeing that many are already much elegent than
> i could possibly do so with my code.
>
> my solution basically use a stack. (i think all of us are doing
> similar) Here's the steps:
>
> • Go thru the file char by char, find a bracket char.
> • check if the one on stack is a matching opening char. If so remove
> it. Else, push the current onto the stack.
> • Repeat the above till end of file.
> • If the stack is not empty, then the file got mismatched brackets.
> Report it.
> • Do the above on all files.

Small correction: my solution works differently (although internally the 
regexp engine will roughly do the same).  So, my approach summarized

- traverse a directory tree
- for each found item of type "file"
-    read the whole content
-    throw it at a regexp which is anchored at the beginning
      and does the recursive parsing
-    report file if the match is shorter than the file

Note: special feature for recursive matching is used which Perl's regexp 
engine likely can do as well but many others don't.

Cheers

	robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

[toc] | [prev] | [next] | [standalone]


#9956

FromXah Lee <xahlee@gmail.com>
Date2011-07-20 03:31 -0700
Message-ID<02e81438-f03a-491f-a105-bc758ebfce83@z7g2000prh.googlegroups.com>
In reply to#9806
i've just cleaned up my elisp code and wrote a short elisp tutorial.

Here:

〈Emacs Lisp: Batch Script to Validate Matching Brackets〉
http://xahlee.org/emacs/elisp_validate_matching_brackets.html

plain text version follows. Please let me know what you think.

am still working on going thru all code in other langs. Will get to
the ruby one, and that perl regex, and the other fixed python ones.
(possibly also the 2 common lisp codes but am not sure they are
runnable as is or just some non-working showoff. lol)

===============================================
Emacs Lisp: Batch Script to Validate Matching Brackets

Xah Lee, 2011-07-19

This page shows you how to write a elisp script that checks thousands
of files for mismatched brackets.

----------------------------------------------------------------
The Problem

------------------------------------------------
Summary

I have 5 thousands files containing many matching pairs. I want to to
know if any of them contains mismatched brackets.

------------------------------------------------
Detail

The matching pairs includes these: () {} [] “” ‹› «» 〈〉 《》 【】 〖〗 「」
『』.

The program should be able to check all files in a dir, and report any
file that has mismatched bracket, and also indicate the line number or
positon where a mismatch occurs.

For those curious, if you want to know what these brackets are, see:

    • Syntax Design: Use of Unicode Matching Brackets as Specialized
Delimiters
    • Intro to Chinese Punctuation with Computer Language Syntax
Perspectives

For other notes and conveniences about dealing with brackets in emacs,
see:

    • Emacs: Defining Keys to Navigate Brackets
    • “extend-selection” at A Text Editor Feature: Extend Selection by
Semantic Unit
    • “select-text-in-quote” at Suggestions on Emacs's mark-word
Command

----------------------------------------------------------------
Solution

Here's outline of steps.

    • Go thru the file char by char, find a bracket char.
    • Check if the one on stack is a matching opening char. If so
remove it. Else, push the current onto the stack.
    • Repeat the above till no more bracket char in the file.
    • If the stack is not empty, then the file got mismatched
brackets. Report it.
    • Do the above on all files.

Here's some interesting use of lisp features to implement the above.

------------------------------------------------
Define Matching Pair Chars as “alist”

We begin by defining the chars we want to check, as a “association
list” (aka “alist”). Like this:

(setq matchPairs '(
                   ("(" . ")")
                   ("{" . "}")
                   ("[" . "]")
                   ("“" . "”")
                   ("‹" . "›")
                   ("«" . "»")
                   ("【" . "】")
                   ("〖" . "〗")
                   ("〈" . "〉")
                   ("《" . "》")
                   ("「" . "」")
                   ("『" . "』")
                   )
      )

If you care only to check for curly quotes, you can remove elements
above. This is convenient because some files necessarily have
mismatched pairs such as the parenthesis, because that char is used
for many non-bracketing purposes (e.g. ASCII smiley).

A “alist” in lisp is basically a list of pairs (called key and value),
with the ability to search for a key or a value. The first element of
a pair is called its key, the second element is its value. Each pair
is a “cons”, like this: (cons mykey myvalue), which can also be
written using this syntax: (mykey . myvalue) for more easy reading.

The purpose of lisp's “alist” is similar to Python's dictionary or
Pretty Home Page's array. It is also similar to hashmap, except that
alist can have duplicate keys, can search by values, maintains order,
and alist is not intended for massive number of elements. Elisp has a
hashmap datatype if you need that. (See: Emacs Lisp Tutorial: Hash
Table.)

(info "(elisp) Association Lists")

------------------------------------------------
Generate Regex String from alist

To search for a set of chars in emacs, we can read the buffer char-by-
char, or, we can simply use “search-forward-regexp”. To use that,
first we need to generate a regex string from our matchPairs alist.

First, we defines/declare the string. Not a necessary step, but we do
it for clarity.

(setq searchRegex "")

Then we go thru the matchPairs alist. For each pair, we use “car” and
“cdr” to get the chars and “concat” it to the string. Like this:

(mapc
 (lambda (mypair) ""
   (setq searchRegex (concat searchRegex (regexp-quote (car mypair))
"|" (regexp-quote (cdr mypair)) "|") )
   )
 matchPairs)

Then we remove the ending “|”.

(setq searchRegex (substring searchRegex 0 -1)) ; remove the ending
“|”

Then, change | it to \\|. In elisp regex, the | is literal. The “regex
or” is \|. And if you are using regex in elisp, elisp does not have a
special regex string syntax, it only understands normal strings. So,
to feed to regex \|, you need to espace the first backslash. So, your
regex needs to have \\|. Here's how we do it:

(setq searchRegex (replace-regexp-in-string "|" "\\|" searchRegex t
t)) ; change | to \\| for regex “or” operation

You could shorten the above into just 2 lines by using \\| in the
“mapc” step and not as a extra step of replacing | by \\|.

See also: emacs regex tutorial.

------------------------------------------------
Implement Stack Using Lisp List

Stack is done using lisp's list. e.g. '(1 2 3). The bottom of stack is
the first element. To add to the stack, do it like this: (setq mystack
(cons newitem mystack)). To remove a item from stack is this: (setq
mystack (cdr mystack)). The stack begin as a empty list: '().

For each element in the stack, we need the char and also its position,
so that we can report the position if the file does have mismatched
pairs.

We use a vector as entries for the stack. Each entry is like this:
(vector char pos). (See: Emacs Lisp Tutorial: List & Vector.)

Here's how to fetch a char from stack bottom, check if current char
matches, push to stack, pop from stack.

; check if current char is a closing char and is in our match pairs
alist.
; use “rassoc” to check alist's set of “values”.
; It returns the first key/value pair found, or nil
(rassoc char matchPairs)

; add to stack
(setq myStack (cons (vector char pos) myStack) )

; pop stack
(setq myStack (cdr myStack) )

------------------------------------------------
Complete Code

Here's the complete code.

;; -*- coding: utf-8 -*-
;; 2011-07-15
;; go thru a file, check if all brackets are properly matched.
;; e.g. good: (…{…}… “…”…)
;; bad: ( [)]
;; bad: ( ( )

(setq inputFile "xx_test_file.txt" ) ; a test file.
(setq inputDir "~/web/xahlee_org/") ; must end in slash

(defvar matchPairs '() "a alist. For each pair, the car is opening
char, cdr is closing char.")
(setq matchPairs '(
                   ("(" . ")")
                   ("{" . "}")
                   ("[" . "]")
                   ("“" . "”")
                   ("‹" . "›")
                   ("«" . "»")
                   ("【" . "】")
                   ("〖" . "〗")
                   ("" . "")
                   ("" . "")
                   ("「" . "」")
                   ("『" . "』")
                   )
      )

(defvar searchRegex "" "regex string of all pairs to search.")
(setq searchRegex "")
(mapc
 (lambda (mypair) ""
   (setq searchRegex (concat searchRegex (regexp-quote (car mypair))
"|" (regexp-quote (cdr mypair)) "|") )
   )
 matchPairs)

(setq searchRegex (replace-regexp-in-string "|$" "" searchRegex t
t)) ; remove the ending “|”

(setq searchRegex (replace-regexp-in-string "|" "\\|" searchRegex t
t)) ; change | to \\| for regex “or” operation

(defun my-process-file (fpath)
  "process the file at fullpath fpath ..."
  (let (myBuffer myStack ξchar ξpos)

    (setq myStack '() ) ; each element is a vector [char position]
    (setq ξchar "") ; the current char found

    (when t
      ;; (not (string-match "/xx" fpath)) ; in case you want to skip
certain files

      (setq myBuffer (get-buffer-create " myTemp"))
      (set-buffer myBuffer)
      (insert-file-contents fpath nil nil nil t)

      (goto-char 1)
      (setq case-fold-search t)
      (while (search-forward-regexp searchRegex nil t)
        (setq ξpos (point)  )
        (setq ξchar (buffer-substring-no-properties ξpos (- ξpos
1))  )

        ;; (princ (format "-----------------------------\nfound char:
%s\n" ξchar) )

        (let ((isClosingCharQ nil) (matchedOpeningChar nil) )
          (setq isClosingCharQ (rassoc ξchar matchPairs))
          (when isClosingCharQ (setq matchedOpeningChar (car
isClosingCharQ) ) )

          ;; (princ (format "isClosingCharQ is: %s\n"
isClosingCharQ) )
          ;; (princ (format "matchedOpeningChar is: %s\n"
matchedOpeningChar) )

          (if
              (and
               (car myStack) ; not empty
               (equal (elt (car myStack) 0) matchedOpeningChar )
               )
              (progn
                ;; (princ (format "matched this bottom item on stack:
%s\n" (car myStack)) )
                (setq myStack (cdr myStack) )
                )
            (progn
              ;; (princ (format "did not match this bottom item on
stack: %s\n" (car myStack)) )
              (setq myStack (cons (vector ξchar ξpos) myStack) ) )
            )
          )
        ;; (princ "current stack: " )
        ;; (princ myStack )
        ;; (terpri )
        )

      (when (not (equal myStack nil))
        (princ "Error file: ")
        (princ fpath)
        (print (car myStack) )
        )
      (kill-buffer myBuffer)
      )
    ))

(require 'find-lisp)

(let (outputBuffer)
  (setq outputBuffer "*xah match pair output*" )
  (with-output-to-temp-buffer outputBuffer
    ;; (my-process-file inputFile)
    (mapc 'my-process-file (find-lisp-find-files inputDir "\\.txt$"))
    (princ "Done deal!")
    )
  )

I added many comments and debug code for easy understanding. If you
are not familiar with the many elisp idioms such as opening file,
buffers, printing to output, see: Emacs Lisp Idioms (for writing
interactive commands) ◇ Text Processing with Emacs Lisp Batch Style.

To run the code, simply open it in emacs. Edit the line at the top for
“inputDir”. Then call “eval-buffer”.

Here's a sample output:

Error file: c:/Users/h3/web/xahlee_org/p/time_machine/
Hettie_Potter_orig.txt
[")" 3625]
Error file: c:/Users/h3/web/xahlee_org/p/time_machine/
Hettie_Potter.txt
[")" 2338]
Error file: c:/Users/h3/web/xahlee_org/p/arabian_nights/xx/v1fn.txt
["”" 185795]
Done deal!

The weird ξ you see in my code is greek x. I use unicode char in
variable name for experimental purposes. You can just ignore it. (See:
Programing Style: Variable Naming: English Words Considered Harmful.)

------------------------------------------------
Advantages of Emacs Lisp

Note that the great advantage of using elisp for text processing,
instead of {perl, python, ruby, …} is that many things are taken care
by the emacs environment.

I don't need to write code to declare file's encoding (emacs
automatically detects). No reading file is involved. Just open, save,
or move thru characters. No code needed for doing safety backup. (the
var “make-backup-files” controls that). You can easily open the files
by its path with a click or key press. I can add just 2 lines so that
clicking on the error char in the output jumps to the location in the
file.

Any elisp script you write inside emacs automatically become extension
of emacs and can be used in a interactive way.

This problem is posted to a few comp.lang newsgroups as a fun
challenge. You can see several solutions in python, ruby, perl, common
lisp, at: a little parsing challenge ☺ (2011-07-17) @ Source
groups.google.com.

 Xah

[toc] | [prev] | [next] | [standalone]


#9981

From"Uri Guttman" <uri@StemSystems.com>
Date2011-07-20 12:31 -0400
Message-ID<87k4bcq5h2.fsf@quad.sysarch.com>
In reply to#9956
a better parsing challenge. how can you parse usenet to keep this troll
from posting on the wrong groups on usenet? first one to do so, wins the
praise of his peers. 2nd one to do it makes sure the filter stays in
place. all the rest will be rewarded by not seeing the troll anymore.

anyone who actually engages in a thread with the troll should parse
themselves out of existance.

uri

-- 
Uri Guttman  --  uri AT perlhunter DOT com  ---  http://www.perlhunter.com --
------------  Perl Developer Recruiting and Placement Services  -------------
-----  Perl Code Review, Architecture, Development, Training, Support -------

[toc] | [prev] | [next] | [standalone]


#9988

Fromrusi <rustompmody@gmail.com>
Date2011-07-20 10:30 -0700
Message-ID<b1168dba-5270-4710-a191-3520e91c7c6d@f17g2000prf.googlegroups.com>
In reply to#9981
On Jul 20, 9:31 pm, "Uri Guttman" <u...@StemSystems.com> wrote:
> a better parsing challenge. how can you parse usenet to keep this troll
> from posting on the wrong groups on usenet? first one to do so, wins the
> praise of his peers. 2nd one to do it makes sure the filter stays in
> place. all the rest will be rewarded by not seeing the troll anymore.
>
> anyone who actually engages in a thread with the troll should parse
> themselves out of existance.

Goedelian paradox: Is this thread in existence?

[toc] | [prev] | [next] | [standalone]


#9989

Frommerlyn@stonehenge.com (Randal L. Schwartz)
Date2011-07-20 12:06 -0700
Message-ID<86zkk822mt.fsf@red.stonehenge.com>
In reply to#9981
>>>>> "Uri" == Uri Guttman <uri@StemSystems.com> writes:

Uri> a better parsing challenge. how can you parse usenet to keep this troll
Uri> from posting on the wrong groups on usenet? first one to do so, wins the
Uri> praise of his peers. 2nd one to do it makes sure the filter stays in
Uri> place. all the rest will be rewarded by not seeing the troll anymore.

Uri> anyone who actually engages in a thread with the troll should parse
Uri> themselves out of existance.

Since the newsgroups: line is not supposed to have spaces in it, that
makes both his post and your post invalid.  Hence, filter on invalid
posts.

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn@stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc.
See http://methodsandmessages.posterous.com/ for Smalltalk discussion

[toc] | [prev] | [next] | [standalone]


#9992

FromJason Earl <jearl@notengoamigos.org>
Date2011-07-20 14:57 -0600
Message-ID<87k4bc3c22.fsf@notengoamigos.org>
In reply to#9989
On Wed, Jul 20 2011, Randal L. Schwartz wrote:

>>>>>> "Uri" == Uri Guttman <uri@StemSystems.com> writes:
>
> Uri> a better parsing challenge. how can you parse usenet to keep this troll
> Uri> from posting on the wrong groups on usenet? first one to do so, wins the
> Uri> praise of his peers. 2nd one to do it makes sure the filter stays in
> Uri> place. all the rest will be rewarded by not seeing the troll anymore.
>
> Uri> anyone who actually engages in a thread with the troll should parse
> Uri> themselves out of existance.
>
> Since the newsgroups: line is not supposed to have spaces in it, that
> makes both his post and your post invalid.  Hence, filter on invalid
> posts.

I suspect that the spaces you are seeing are being added by Gnus.  I see
them too (and I see them in your post as well), but they disappear when
I use "C-u g" and view the source of the posts.

Jason

[toc] | [prev] | [next] | [standalone]


#9893

FromXah Lee <xahlee@gmail.com>
Date2011-07-19 09:54 -0700
Message-ID<2a67a8cd-d3f0-4af9-9105-6551344b0277@t8g2000prm.googlegroups.com>
In reply to#9688
On Sunday, July 17, 2011 2:48:42 AM UTC-7, Raymond Hettinger wrote:
> On Jul 17, 12:47 am, Xah Lee <xah...@gmail.com> wrote:
> > i hope you'll participate. Just post solution here. Thanks.
>
> http://pastebin.com/7hU20NNL

just installed py3.
there seems to be a bug.
in this file

http://xahlee.org/p/time_machine/tm-ch04.html

there's a mismatched double curly quote. at position 28319.

the python code above doesn't seem to spot it?

here's the elisp script output when run on that dir:

Error file: c:/Users/h3/web/xahlee_org/p/time_machine/tm-ch04.html
["“" 28319]
Done deal!

 Xah

[toc] | [prev] | [next] | [standalone]


#9904

FromThomas Jollans <t@jollybox.de>
Date2011-07-19 20:07 +0200
Message-ID<mailman.1266.1311098837.1164.python-list@python.org>
In reply to#9893
On 19/07/11 18:54, Xah Lee wrote:
> On Sunday, July 17, 2011 2:48:42 AM UTC-7, Raymond Hettinger wrote:
>> On Jul 17, 12:47 am, Xah Lee <xah...@gmail.com> wrote:
>>> i hope you'll participate. Just post solution here. Thanks.
>>
>> http://pastebin.com/7hU20NNL
> 
> just installed py3.
> there seems to be a bug.
> in this file
> 
> http://xahlee.org/p/time_machine/tm-ch04.html
> 
> there's a mismatched double curly quote. at position 28319.
> 
> the python code above doesn't seem to spot it?
> 
> here's the elisp script output when run on that dir:
> 
> Error file: c:/Users/h3/web/xahlee_org/p/time_machine/tm-ch04.html
> ["“" 28319]
> Done deal!


That script doesn't check that the balance is zero at the end of file.

Patch:

--- ../xah-raymond-old.py	2011-07-19 20:05:13.000000000 +0200
+++ ../xah-raymond.py	2011-07-19 20:03:14.000000000 +0200
@@ -16,6 +16,8 @@
         elif c in closers:
             if not stack or c != stack.pop():
                 return i
+    if stack:
+        return i
     return -1

 def scan(directory, encoding='utf-8'):

[toc] | [prev] | [next] | [standalone]


#10021

FromXah Lee <xahlee@gmail.com>
Date2011-07-21 05:58 -0700
Message-ID<caf3941f-ec97-447d-bb84-c02dbcaf2487@h7g2000prf.googlegroups.com>
In reply to#9904
On Jul 19, 11:07 am, Thomas Jollans <t...@jollybox.de> wrote:
> On 19/07/11 18:54, Xah Lee wrote:
>
>
>
>
>
>
>
>
>
> > On Sunday, July 17, 2011 2:48:42 AM UTC-7, Raymond Hettinger wrote:
> >> On Jul 17, 12:47 am, Xah Lee <xah...@gmail.com> wrote:
> >>> i hope you'll participate. Just post solution here. Thanks.
>
> >>http://pastebin.com/7hU20NNL
>
> > just installed py3.
> > there seems to be a bug.
> > in this file
>
> >http://xahlee.org/p/time_machine/tm-ch04.html
>
> > there's a mismatched double curly quote. at position 28319.
>
> > the python code above doesn't seem to spot it?
>
> > here's the elisp script output when run on that dir:
>
> > Error file: c:/Users/h3/web/xahlee_org/p/time_machine/tm-ch04.html
> > ["“" 28319]
> > Done deal!
>
> That script doesn't check that the balance is zero at the end of file.
>
> Patch:
>
> --- ../xah-raymond-old.py       2011-07-19 20:05:13.000000000 +0200
> +++ ../xah-raymond.py   2011-07-19 20:03:14.000000000 +0200
> @@ -16,6 +16,8 @@
>          elif c in closers:
>              if not stack or c != stack.pop():
>                  return i
> +    if stack:
> +        return i
>      return -1
>
>  def scan(directory, encoding='utf-8'):

Thanks a lot for the fix Raymond.

Though, the code seems to have a minor problem.
It works, but the report is wrong.
e.g. output:

30068: c:/Users/h3/web/xahlee_org/p/time_machine\tm-ch04.html

that 30068 position is the last char in the file.
The correct should be 28319. (or at least point somewhere in the file
at a bracket char that doesn't match.)

Today, i tried 3 more scripts. 2 fixed python3 versions, 1 ruby, all
failed again. I've reported the problems i encounter at python or ruby
newsgroups. If you are the author, a fix is very much appreciated.
I'll get back to your code and eventually do a blog of summary of all
different lang versions.

Am off to test that elaborate perl regex now... cross fingers.

 Xah. Mood: quite discouraged.

[toc] | [prev] | [next] | [standalone]


#10026

FromIan Kelly <ian.g.kelly@gmail.com>
Date2011-07-21 08:26 -0600
Message-ID<mailman.1320.1311258423.1164.python-list@python.org>
In reply to#10021
On Thu, Jul 21, 2011 at 6:58 AM, Xah Lee <xahlee@gmail.com> wrote:
> Thanks a lot for the fix Raymond.

That fix was from Thomas Jollans, not Raymond Hettinger.

> Though, the code seems to have a minor problem.
> It works, but the report is wrong.
> e.g. output:
>
> 30068: c:/Users/h3/web/xahlee_org/p/time_machine\tm-ch04.html
>
> that 30068 position is the last char in the file.
> The correct should be 28319. (or at least point somewhere in the file
> at a bracket char that doesn't match.)

Previously you wrote:

> If a file has mismatched matching-pairs, the script will display the
> file name, and the  line number and column number of the first
> instance where a mismatched bracket occures. (or, just the char number
> instead (as in emacs's “point”))

I submit that as the file contains no mismatched brackets (only an
orphan bracket), the output is correct to specification (indeed you
did not define any output for this case), if not necessarily useful.

In other words, stop being picky.  You may be willing to spend an hour
or moe on this, but that doesn't mean anybody else is.  Raymond gave
you a basically working Python solution, but forgot one detail.
Thomas fixed that detail for you but didn't invest the time to rewrite
somebody else's function to get the output "correct".  Continuing to
harp on it at this point is verging on trolling.

[toc] | [prev] | [next] | [standalone]


#10028

FromXah Lee <xahlee@gmail.com>
Date2011-07-21 08:36 -0700
Message-ID<65c72670-9030-41fa-af4d-bcf5189d0aae@f17g2000prf.googlegroups.com>
In reply to#10026
Ok. Here's a preliminary report.

〈Lisp, Python, Perl, Ruby … Code to Validate Matching Brackets〉
http://xahlee.org/comp/validate_matching_brackets.html

it's taking too much time to go thru.

right now, i consider only one valid code, by Raymond Hettinger (with
minor edit from others).

right now, there's 2 other possible correct solution. One by Robert
Klemme but requires ruby19 but i only have ruby18x. One by Thomas
Jollans in Python 3 but didn't run on my machine perhaps due to some
unix/Windows issue, yet to be done.

the other 3 or 4 seems to be incomplete or just suggestion of ideas.

i haven't done extensive testing on my own code neither.
I'll revisit maybe in a few days.

Feel free to grab my report and make it nice. If you would like to fix
your code, feel free to email.

 Xah

On Jul 21, 7:26 am, Ian Kelly <ian.g.ke...@gmail.com> wrote:
> On Thu, Jul 21, 2011 at 6:58 AM, Xah Lee <xah...@gmail.com> wrote:
> > Thanks a lot for the fix Raymond.
>
> That fix was from Thomas Jollans, not Raymond Hettinger.
>
> > Though, the code seems to have a minor problem.
> > It works, but the report is wrong.
> > e.g. output:
>
> > 30068: c:/Users/h3/web/xahlee_org/p/time_machine\tm-ch04.html
>
> > that 30068 position is the last char in the file.
> > The correct should be 28319. (or at least point somewhere in the file
> > at a bracket char that doesn't match.)
> Previously you wrote:
> > If a file has mismatched matching-pairs, the script will display the
> > file name, and the  line number and column number of the first
> > instance where a mismatched bracket occures. (or, just the char number
> > instead (as in emacs's “point”))
>
> I submit that as the file contains no mismatched brackets (only an
> orphan bracket), the output is correct to specification (indeed you
> did not define any output for this case), if not necessarily useful.
>
> In other words, stop being picky.  You may be willing to spend an hour
> or moe on this, but that doesn't mean anybody else is.  Raymond gave
> you a basically working Python solution, but forgot one detail.
> Thomas fixed that detail for you but didn't invest the time to rewrite
> somebody else's function to get the output "correct".  Continuing to
> harp on it at this point is verging on trolling.

[toc] | [prev] | [next] | [standalone]


Page 1 of 4  [1] 2 3 4  Next page →

Back to top | Article view | comp.lang.python


csiph-web