Deutsch English Français Italiano |
<103kcpp$3m0dd$1@dont-email.me> View for Bookmarking (what is this?) Look up another Usenet article |
Path: news.eternal-september.org!eternal-september.org!.POSTED!not-for-mail From: "B. Pym" <Nobody447095@here-nor-there.org> Newsgroups: comp.lang.lisp Subject: Re: string search and assignment Date: Thu, 26 Jun 2025 21:07:06 -0000 (UTC) Organization: A noiseless patient Spider Lines: 75 Message-ID: <103kcpp$3m0dd$1@dont-email.me> References: <v61kut$1p0ar$1@dont-email.me> Injection-Date: Thu, 26 Jun 2025 23:07:07 +0200 (CEST) Injection-Info: dont-email.me; posting-host="4b1bb7d566f46488e77f5ce601d47784"; logging-data="3867053"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX188UYZ+1Y7jUjkkA65yqPas" User-Agent: XanaNews/1.18.1.6 Cancel-Lock: sha1:2UJ4rwtvfUdEhv6qeDLMCV6bZGg= B. Pym wrote: > Kent M. Pitman wrote: > > > ... What i want to do is start at the beginning of the > > file( which I can do) and search for the word "entity". > > Once I find this, I want to assign the next word to a > > variable. ... > > > > Use WITH-OPEN-FILE to open the stream. It will let you specify > > a variable to which the stream is bound. The I/O routines all > > take a stream as argument. e.g., > > > > (defun find-word-association-in-file (word file) > > (with-open-file (stream file :direction :input) > > (loop > > (let ((line (read-line stream nil nil))) > > (declare (type string line)) > > (unless line (return nil)) > > (let ((pos1 (position #\Space line :test #'char-equal))) > > (when (and pos1 (string-equal word line :end2 pos1)) > > (let ((pos2 (position #\Space line > > :test (complement #'char-equal) > > :start pos1))) > > (when pos2 > > (return (subseq line pos2 > > (position #\Space line > > :test #'char-equal > > :start pos2))))))))))) > > > > Given a data file "delete-me.text" containing: > > > > FOO OOF > > BAR RAB XYZZY > > BAZ ZAB PLOVER PLUGH > > NUL NIL > > > > I find that: > > > > (find-word-association-in-file "FOO" "delete-me.text") => "OOF" > > (find-word-association-in-file "BAZ" "delete-me.text") => "ZAB" > > (find-word-association-in-file "NUL" "delete-me.text") => "NIL" > > (find-word-association-in-file "GEE" "delete-me.text") => NIL Scheme (define (find-word-association-in-file word file) (with-input-from-file file (lambda() (let go ((s (read))) (cond ((eof-object? s) #f) ((equal? s word) (read)) (#t (go (read)))))))) (find-word-association-in-file 'FOO "delete-me.text") ===> OOF (find-word-association-in-file 'BAZ "delete-me.text") ===> ZAB (find-word-association-in-file 'PLOVER "delete-me.text") ===> PLUGH (find-word-association-in-file 'OOF "delete-me.text") ===> BAR (find-word-association-in-file 'NOWHERE "delete-me.text") ===> #f