从文件中返回单词列表 [英] Returning a List of Words from a File

查看:93
本文介绍了从文件中返回单词列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的下一个项目是编写a子手游戏.我认为这将有助于我复习字符串和文件I/O.

My next project is writing a hangman game. I figured it would help me brush up on strings and file I/O.

目前,我一直坚持将字符串文件读入列表中.我试图避免使用全局变量,所以有人可以向我指出正确的方向,以使此(可能是损坏的)代码成为返回列表的函数吗?

Currently, i'm stuck on reading in a file of strings into a list. I'm trying to avoid global variables, so could someone point me in the right direction to make this (probably broken) code into a function that returns a list?

(defun read-word-list ()
  "Returns a list of words read in from a file."
  (let ((word-list (make-array 0 
                 :adjustable t
                 :fill-pointer 0)))
       (with-open-file (stream #p"wordlist.txt")
     (loop for line = (read-line stream)
        while line
          (push line word-list)))
       (select-target-word word-list)))))

推荐答案

您只需几行代码就可以将单词读为Lisp符号:

You can read-in the words as Lisp symbols, with just a few lines of code:

(defun read-words (file-name)
    (with-open-file (stream file-name)
      (loop while (peek-char nil stream nil nil)
           collect (read stream))))

示例输入文件-words.txt:

Example input file - words.txt:

attack attempt attention attraction authority automatic awake 
bright broken brother brown brush bucket building 
comfort committee common company comparison competition

读取文件:

> (read-words "words.txt")
=> (ATTACK ATTEMPT ATTENTION ATTRACTION AUTHORITY AUTOMATIC AWAKE BRIGHT BROKEN BROTHER BROWN BRUSH BUCKET BUILDING COMFORT COMMITTEE COMMON COMPANY COMPARISON COMPETITION)

可以通过将符号括在管道(|)中或将其声明为字符串来保留大小写:

The case could be preserved by enclosing the symbols in pipes (|) or declaring them as strings:

|attack| "attempt" ...

阅读而不会丢失案子

> (read-words "words.txt")
=> (|attack| "attempt" ...)

这篇关于从文件中返回单词列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆