我有一个小文本文件,我想使用autohotkey提取一些值。
文本文件的内容示例:
Date: 2014-12-02 12:06:47
Study: G585.010.411
Image: 6.24
Tlbar: 2.60
Notes: 0.74
我目前的代码:
FileReadLine, datetime, C:\File.txt, 1
datedsp := SubStr(datetime, 7)
Sleep 500
FileReadLine, study, C:\File.txt, 2
studydsp := SubStr(study, 7)
Sleep 500
FileReadLine, image, C:\File.txt, 3
imgdsp := SubStr(image, 7)
Sleep 500
FileReadLine, notes, C:\File.txt, 5
notesdsp := SubStr(notes, 7)
Sleep 500
MsgBox %datedsp%
MsgBox %studydsp%
MsgBox %imgdsp%
MsgBox %notesdsp%
我想要做的就是获取每一行的值并将其分配给变量。例如, studydsp 值为G58500411, imagedsp 值为6.24, datedsp 值为2014-12-02 12:06:47
有没有以更好的方式实现这一目标?
此代码可能存在的问题:
答案 0 :(得分:3)
您可以使用FileRead和RegExMatch
var:="
(
Date: 2014-12-02 12:06:47
Study: G585.010.411
Image: 6.24
Tlbar: 2.60
Notes: 0.74
)"
;~ FileRead, var, C:\file.txt
pos:=1
while pos := RegExMatch(var, "\s?(.*?):(.*?)(\v|\z)", m, pos+StrLen(m))
%m1% := m2
msgbox % "Date holds " date
. "`nStudy holds " Study
. "`nImage holds " Image
. "`nTlbar holds " Tlbar
. "`nNotes holds " Notes
只需删除var部分并取消注释文件读取行,至少这是一种方法:)
希望有所帮助
答案 1 :(得分:2)
基本上与@ blackholyman的答案相同,但通过构建值映射使用基于对象的方法:
fileCont =
(
Date: 2014-12-02 12:06:47
Study: G585.010.411
Image: 6.24
Tlbar: 2.60
Notes: 0.74
)
valueMap := {}
; Alternatively, use: Loop, Read, C:\file.txt
Loop, Parse, fileCont, `r`n
{
RegExMatch(A_LoopField, "(.*?):(.*)", parts)
; Optionally make keys always lower case:
; StringLower, parts1, parts1
valueMap[Trim(parts1)] := Trim(parts2)
}
msgbox % "Date = " valueMap["Date"]
. "`nImage = " valueMap["Image"]
; We can also iterate over the map
out := ""
for key, val in valueMap
{
out .= key "`t= " val "`n"
}
msgbox % out