从文件中查找数据,并将它们存储为变量

Looking up data from a file, and storing them as variables

我是 autohotkey 的新手,我不知道如何解决这个问题。任何帮助表示赞赏。 我有 list.txt,其中包括这样的 ID 和名称:

list.txt:
123124 - whatever
834019 - sometext
3980   - afjalkfj

我需要一个可以执行以下操作的函数

lookup(id, name){
    ** The function here should lookup for the id inserted 
 then save ONLY the data related to it in variable x (not the full line)
}

示例

lookup(834019, x)
%x% = sometext

请帮我做一下。谢谢!

在这种情况下你需要的是

  • FileRead 将文件内容读入变量。

  • 一个parsing loop来解析每一行的文本。

  • StrSplit()函数将每一行的文本拆分成一个 使用指定定界符的子字符串数组。

在这种情况下,第二个参数(名称)是多余的。你可以省略它:

x := lookup(834019)
MsgBox, % x

MsgBox, % lookup(3980)


lookup(id) {
    FileRead, Contents, list.txt   ; read the file's contents into the variable "Contents"
    if not ErrorLevel  ; Successfully loaded.
    {
        Loop, parse, Contents, `n, `r  ; parse the text of each line 
        {
            word_array1 := StrSplit(A_LoopField," - ").1  ; store the first substring into the variable "word_array1"
            word_array1 := Trim(word_array1, " `t") ; trim spaces and tabs in this variable
            If (word_array1 = id)
            {
                name := StrSplit(A_LoopField," - ").2
                name := Trim(name, " `t")
                return name
            }
        }
        Contents := ""  ; Free the memory.
    }
    else
        MsgBox, A problem has been encountered while loading the File Contents
}