2014-12-02 177 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