AutoIt文本统计脚本起始位置为0时返回全0的问题排查
问题分析与修复方案
我一眼就揪出问题啦——你踩了索引规则不匹配的坑,还有个行数统计的小错误,这俩凑一起导致开头选中时统计全为0。咱们一步步拆解:
核心问题1:索引体系不兼容
_GUICtrlEdit_GetSel返回的选中位置是0-based(从0开始计数),但AutoIt的StringMid函数是1-based(从1开始计数)。当你选中起始位置为0时,StringMid($input_str, 0, ...)会直接返回空字符串——它根本不认0作为起始索引,这就是所有统计结果归0的根源!
核心问题2:行数统计调用错误
你写的_GUICtrlEdit_GetLineCount($selstring)是错的,这个函数的参数必须是Edit控件的句柄,不能传选中的字符串。要统计选中内容的行数,得自己处理字符串里的换行符。
修复后的完整代码
$input_str = GUICtrlRead($Textbox) $selpos = _GUICtrlEdit_GetSel($Textbox) MsgBox($MB_OK, $selpos[0], $selpos[1]) # 修复:0-based转1-based起始索引 $selstring = StringMid($input_str, $selpos[0] + 1, ($selpos[1] - $selpos[0])) $WordArray = StringRegExp($selstring, "[\s\.:;,]*([a-zA-Z0-9-_]+)[\s\.:;,]*", 3) $SingleQuotes = StringRegExp($selstring, "'", 3) $Result = "" $wordCount = UBound($WordArray) - UBound($SingleQuotes) $Seconds = $wordCount / 2 If $Seconds >= 3600 Then $hourNum = Int($Seconds / 3600) $Result &= $hourNum & " hour" & ($hourNum >=2 ? "s " : " ") EndIf $remainingAfterHours = Mod($Seconds, 3600) If $remainingAfterHours >= 60 Then $minNum = Int($remainingAfterHours / 60) $Result &= $minNum & " minute" & ($minNum >=2 ? "s " : " ") EndIf $remainingAfterMins = Mod($Seconds, 60) If $remainingAfterMins > 0 Then $secNum = Int($remainingAfterMins) $Result &= $secNum & " second" & ($secNum >=2 ? "s " : " ") EndIf # 修复:统计选中内容的行数 $lineArray = StringSplit($selstring, @CRLF) $lineCount = UBound($lineArray) - 1 # 处理最后一行末尾无换行的边界情况 If StringRight($selstring, 2) = @CRLF Then $lineCount += 1 EndIf MsgBox($MB_OK, "Selection Properties", _ "Number of characters (with spaces): " & StringLen($selstring) & @CRLF & _ "Number of Characters (without spaces): " & StringLen(StringStripWS($selstring, 8)) & @CRLF & _ "Number of words: " & $wordCount & @CRLF & _ "Number of lines: " & $lineCount & @CRLF & _ "Estimated speaking time: " & $Result _ )
关键修复点说明
- 索引转换:给
$selpos[0]加1,让0-based的起始位置适配StringMid的1-based要求,从文本开头选中的内容就能正确截取了。 - 行数统计:用
StringSplit拆分选中字符串的换行符,通过数组长度计算行数,同时处理最后一行末尾没有换行的特殊情况。 - 代码简化:把重复的单复数判断改成三元运算符,让代码更清爽。
你试试这段代码,从文本开头选中内容时应该就能正常统计啦!
内容的提问来源于stack exchange,提问作者DED1
相关产品推荐
相关产品推荐

