【问题标题】:why am i unable to read strings form a txt file from net logo?为什么我无法从 net logo 的 txt 文件中读取字符串?
【发布时间】:2015-01-28 23:56:31
【问题描述】:

我正在尝试从 txt 文件中读取 net logo 中的以下行:

工作1 1 1 15 25 90 3 1111 1100 0010 0110 1011 0 0 0 0 0 0 0 0 0 0 0

但是,我收到的所有时间:预期一个常量(第 1 行,第 5 个字符)

在这种情况下,我有很多问题。

A) 如何让 netlogo 读取字符串“Job1”?

B) 考虑到第 10 个数字是二进制,我怎样才能将其作为字符串而不是数字?

感谢您的回答。

大猩猩粉丝

【问题讨论】:

  • 在此列表中搜索类似问题。另见subversion.american.edu/aisaac/notes/…
  • 你尝试读取该行的代码是什么?
  • file-open "file.txt" set name file-read ;;得到这份工作1。 . .设置代码文件读取;;得到 0010 但它得到它作为一个数字。我需要它作为字符串。 . .文件关闭

标签: file text netlogo


【解决方案1】:

我不太确定我是否真的得到了你想要达到的目标。您想将“txt 文件”的所有元素作为字符串读取,但用空格分隔吗? 如果是,您可以尝试逐字符读取文件以检查空格之间的字符串长度。然后再次浏览文件并提取这些字符串。这是如何实现它的示例代码。也许还有更优雅的版本,但这个版本对我来说很完美:

globals
[
  char-list
  char-counter
  string-list
  current-char
]

to read

set char-counter 0
set char-list []
set string-list []
set current-char 0

;; Open the file and go through it, char by char to check where the blank spaces are
file-open "in.txt"

while [file-at-end? = false]
[
  ;; Save current char
  set current-char file-read-characters 1

  ;; Check if the char is a blank space...
  ifelse (current-char != " ")
    ;; If not, increase the length of the current string
    [
      set char-counter char-counter + 1
    ]
    ;; If yes, save the length of the previous string, and reset the char-counter
    [
      set char-list lput char-counter char-list
      set char-counter 0
    ]
]

file-close  

;; Now read the file again and extract only the strings which are not blank spaces
file-open "in.txt"

let i 0
while [i < length char-list]
[
  ;; Read the next number of characters as defined by the previously created char-list
  set string-list lput file-read-characters item i char-list string-list

  ;; Skip 1 space:
  set current-char file-read-characters 1

  ;; Increase i
  set i i + 1
]

file-close

end

【讨论】:

  • 工作完美,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-09
  • 1970-01-01
  • 2012-10-10
  • 2020-08-11
  • 1970-01-01
相关资源
最近更新 更多