You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改AutoHotkey随机选行代码,使列表文本行单独分行?

解决AutoHotkey多行列表赋值与空行问题

针对你的需求,我们可以利用AutoHotkey 1.1的多行文本赋值语法让每个列表条目单独分行,同时通过优化字符串分割逻辑避免空行问题。修改后的代码如下:

Random, rand1, 1, 4
Random, rand2, 1, 4
Random, rand3, 1, 4

; 定义3个多行列表:每个条目单独一行,括号内不要留多余空行
list1 =
(
1st text-line
2nd text-line
3rd text-line
4th text-line
)

list2 =
(
5th text-line
6th text-line
7th text-line
8th text-line
)

list3 =
(
9th text-line
10th text-line
11th text-line
12th text-line
)

; 按换行分割列表,同时忽略回车符(避免Windows换行符带来的空元素)
selectedLine1 := StrSplit(list1, "`n", "`r")[rand1]
selectedLine2 := StrSplit(list2, "`n", "`r")[rand2]
selectedLine3 := StrSplit(list3, "`n", "`r")[rand3]

; 拼接并复制到剪贴板
clipboard = %selectedLine1%`n%selectedLine2%`n%selectedLine3%

; 弹窗预览结果
msgbox, Randoms: %rand1%, %rand2%, %rand3%`nSelected lines:`n%selectedLine1%`n%selectedLine2%`n%selectedLine3%

关键改动说明

  • 多行赋值方式:使用=后接(...)的语法,让每个列表条目单独分行,编辑长文本时更清晰。注意括号内部不要留多余的空行(包括列表最后一行的下方),否则会引入空元素。
  • 字符串分割优化:用StrSplit(列表变量, "n", "r")分割,第二个参数是换行符,第三个参数是要忽略的字符(回车符),这样能自动处理Windows系统的\r\n换行格式,避免分割出空字符串。
  • 保留原有逻辑:随机数生成、结果拼接和剪贴板复制的逻辑完全保留,确保功能和之前一致。

如果不小心在多行列表里留了空行,也可以通过过滤空元素来避免问题,比如:

; 分割后过滤空元素
list1Arr := StrSplit(list1, "`n", "`r")
Loop % list1Arr.Length()
    if (list1Arr[A_Index] = "")
        list1Arr.RemoveAt(A_Index)
selectedLine1 := list1Arr[rand1]

这种方式更健壮,即使列表里有多余空行也不会影响结果。

内容的提问来源于stack exchange,提问作者rx65m

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 04:10:41