2014-12-02 180 views
1

我有一个小文本文件,我想使用autohotkey提取一些值。文本文件的内容使用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,的预期值为值将为2014-12-02 12:06:47。

有没有办法以更好的方式实现这一点?

使用此代码可能的问题:(?)

  1. 我无法从日线串可能是由于在 空间开始
  2. 我不能让无论是最新的SUBSTR值(参见第1期)或 研究(因为特殊字符的吧?)

回答

3

您可以使用FileReadRegExMatch

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部分,并取消对FILEREAD线,至少这就是做一个办法:)

希望它有助于

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