Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

LISP: Find occurrences of each word in a sentence.

Can someone please explain to me how I search for the occurrences of each word in a sentence, such as "the cat sat on the mat" in Common lisp ?

The user has to have inputted this line of text before hand and then the occurrences must be counted from that. Any help on even where to start would help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Have a look at split-by-one-space in The Common Lisp Cookbook

(defun split-by-one-space (string)
    "Returns a list of substrings of string
     divided by ONE space each.
     Note: Two consecutive spaces will be seen as
     if there were an empty string between them."

    (loop for i = 0 then (1+ j)
          as j = (position #Space string :start i)
          collect (subseq string i j)
          while j))

Now you could just use a hash table with equal as test and perhaps use mapc on the list to get a key and frequency hash. Then you have what you wanted in the hash table.

Alternatively (and slower) would be to count the first element with (count (car lst) lst :test #'equal) and process the rest of the list with (remove (car lst) lst :test #'equal). When the filtered list is empty you're done.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...