LISP: Find occurrences of each word in a sentence.

2019-09-21 05:49发布

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.

标签: lisp
1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-21 06:18

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.

查看更多
登录 后发表回答