AHK V1 读取TXT文件并随机输出内容

本文将介绍如何使用 AutoHotkey V1 读取 TXT 文件内容,并随机选择一小段内容,按下 'A' 键输出。

代码示例

Random, randomLine, 1, % LinesInFile('your_file.txt') ; 获取文件行数
randomParagraph := ReadRandomParagraph('your_file.txt', randomLine)
randomParagraph := Trim(randomParagraph) ; 去除段落前后的空格和换行符
SendInput, {Raw}%randomParagraph%{a} ; 发送复制的段落并按下 'A' 键输出

; 获取文件行数
LinesInFile(file) {
    lineCount := 0
    FileOpen, fileHandle, %file%, r
    while !FileHandle.AtEOF()
    {
        FileHandle.ReadLine()
        lineCount++
    }
    FileHandle.Close()
    return lineCount
}

; 读取随机段落
ReadRandomParagraph(file, lineNum) {
    lineCount := 0
    randomPara := ''
    FileOpen, fileHandle, %file%, r
    while !FileHandle.AtEOF()
    {
        line := FileHandle.ReadLine()
        lineCount++
        if (lineCount = lineNum) ; 找到随机行号
        {
            if (line = '') ; 当前行为空行,则继续读取下一行
                continue
            randomPara .= line '`n' ; 拼接随机段落
        }
    }
    FileHandle.Close()
    return randomPara
}

使用说明

  1. 将上述代码保存为 AutoHotkey V1 脚本文件(例如 'random_output.ahk')。
  2. 将代码中的 'your_file.txt' 替换为您要读取的 TXT 文件路径。
  3. 运行脚本,它将随机选择一小段内容并按下键盘上的 'A' 键输出。

代码解析

  • LinesInFile(file) 函数:获取指定文件 file 的行数。
  • ReadRandomParagraph(file, lineNum) 函数:读取指定文件 file 中第 lineNum 行开始的一段内容。
  • 主程序:
    • 首先使用 LinesInFile() 函数获取文件行数。
    • 然后使用 Random 函数生成一个随机行号 randomLine
    • 使用 ReadRandomParagraph() 函数读取随机行号开始的一段内容,并去除首尾空格和换行符。
    • 最后使用 SendInput 命令将读取的内容发送到当前窗口并按下 'A' 键输出。

总结

通过以上代码,您可以轻松地使用 AutoHotkey V1 实现读取 TXT 文件并随机输出内容的功能。您可以根据自己的需求修改代码,例如更改输出的按键或修改随机段落的选取规则。

AHK V1 读取TXT文件并随机输出内容

原文地址: https://www.cveoy.top/t/topic/bHnr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录