例如,如果我输入字符序列
“你好世界” H = 1 e = 1 l = 3 o - 2 r = 1 w = 1 d = 1
有人能帮我吗
我在网上找到了这段代码,但我不明白它,我想要一个更简单的代码
(defun letter-freq (file)
(with-open-file (stream file)
(let ((str (make-string (file-length stream)))
(arr (make-array 256 :element-type 'integer :initial-element 0)))
(read-sequence str stream)
(loop for c across str do (incf (aref arr (char-code c))))
(loop for c from 32 to 126 for i from 1 do
(format t "~c: ~d~a"
(code-char c) (aref arr c)
(if (zerop (rem i 8)) #\newline #\tab))))))
(letter-freq "test.lisp")
Run Code Online (Sandbox Code Playgroud)
上面的代码是针对 ASCII 字符的。如果您想对任何可能的字符执行相同的操作,可以使用哈希表。
\n\n(defun letter-freq (file)\n (with-open-file (stream file)\n (let ((str (make-string (file-length stream)))\n (ht (make-hash-table)))\n (read-sequence str stream)\n (loop :for char :across str :do\n (incf (gethash char ht 0)))\n (maphash (lambda (k v)\n (format t "~@C: ~D~%" k v))\n ht))))\nRun Code Online (Sandbox Code Playgroud)\n\n~@Cformat 指令打印chara\xd1\x81ter,就像通过prin1.