在Bash中创建变量数组

时间:2018-01-17 05:49:05

标签: arrays bash tabular

我认为我不能谷歌这个答案的原因,是因为我不知道使用的条款。如果这篇文章令人沮丧,那么道歉。

我想要创建的是一个多部分变量数组;这样一组关键字就可以与相应的MQTT主题相对应。背景(与问题无关) - 我打算将自然语言转换为自动触发器;一旦我有了我的表,一个函数可以将口语句子与我想要创建的数组/表进行比较,如果关键字匹配,则发送相应的MQTT消息。我想使用这种表/数组方法,以便轻松更新整体解决方案。

在某种想象的语言中,构建这样一个表的代码可能如下所示:

keywords            mqtt
--------            --------
lounge tv on        lounge/tv{on}       
lounge tv off       lounge/tv{off}       
bedroom tv on       bedroom/tv{on}       
bedroom tv off      bedroom/tv{off} 

我猜结果将是一个包含“keywords”和“mqtt”列标题的表格,可能会显示如下。我不在乎它是如何显示的,这只是为了帮助解释我自己。

{{1}}

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

您要求的是一个名为关联数组的bash 4功能。

declare -A commands=(
  ["lounge tv on"]="lounge/tv{on}"
  ["lounge tv off"]="lounge/tv{off}"
  ["bedroom tv on"]="bedroom/tv{on}"
  ["bedroom tv off"]="bedroom/tv{off}"
)

查找类似于以下内容:

input="lounge tv on"
echo "Running command: ${commands[$input]}"

...而且作业类似于:

commands["new command"]="new/command{parameter}"

BashFAQ #6the bash-hackers' wiki page on arrays中详细介绍了关联数组。

答案 1 :(得分:-1)

最简单的方法是创建一个单独的文件,而不是创建一个表。

所以这是commands.txt的内容:

import os
import itertools

path = "SRC PATH"
for root, dirs, files in os.walk(path):
    for file1, file2 in itertools.izip_longest(files[::2], files[1::2]):
        im1 = cv2.imread(file1)
        if file2:
            im2 = cv2.imread(file2)

..以及处理文件的代码:

lounge tv on;lounge/tv{on}
lounge television on;lounge/tv{on}
lounge tv off;lounge/tv{off}
lounge television off;lounge/tv{off}
相关问题