用相同长度的随机字符串替换文本的宏

用相同长度的随机字符串替换文本的宏

我正在使用 LuaLaTeX 替换,尝试找到一种方法来用相同长度的随机字符替换宏中的字符串。

chickenize包提供了randomchars对整个段落执行此操作的功能。但是,我无法让它工作只是TeX 宏的参数,并在尝试创建如下宏时出现错误或不显示任何内容:

\newcommand{\rndm}[1]{\directlua{randomchars(#1)}}

答案1

就是这样。请注意,输入和输出字符可以是(几乎)任意的 utf8 编码字符。(在输出时,您需要验证输出字符是否确实存在于所使用的字体中。)如果字符是 TeX 特殊字符(例如和),&$确保将它们转义为\\&\\$等。输入字符串中的空格会被保留,但标点符号不会得到任何优先处理。

在此处输入图片描述

% !TEX TS-program = lualatex
\documentclass{article}
\usepackage{luacode} % for 'luacode' environment and '\luastring' macro
\begin{luacode}
function rndstring ( inputstring )
  local outputstring, choices, mm, nn
  mm = unicode.utf8.len(inputstring) -- no. of utf8-encoded characters in input string

  -- Place candidate replacement characters in a Lua table:
  choices = { 
     "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", 
     "\\#", "\\$", "\\%", "\\%", "\\&", "\\_", "\\textbackslash{}",
     "*", "+", "-", "/", "(", ")", "[", "]", "\\{", "\\}",
     "<", "=", ">", "?", "@", "\\textasciitilde{}",
     "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", 
     "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", 
     "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", 
     "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
   }
  -- Number of rows in 'choices' table
  nn = #choices 

  -- Generate the outputstring in a 'for' loop:
  outputstring = ""
  for i = 1 , mm do
     if unicode.utf8.sub ( inputstring , i , i ) == " "  then
         outputstring = outputstring .. " " -- preserve space char.
     else -- choose a new char randomly from 'choices' table
         outputstring = outputstring .. choices[ math.random ( nn ) ]
     end
   end

   return ( outputstring )
end
\end{luacode}

%% Define a LaTeX macro to invoke the Lua function
\newcommand\rndstring[1]{\directlua{tex.sprint(rndstring(\luastring{#1}))}}

%% test strings to feed to '\rndstring':
\newcommand\stringA{Hello World}
\newcommand\stringB{Hello Владимир öäüß}
\newcommand\stringC{Once upon a time, there was ...}

\begin{document}
\ttfamily % optional

\rndstring{\stringA}\par\rndstring{\stringB}\par\rndstring{\stringC}

\bigskip
\rndstring{\stringA}\par\rndstring{\stringB}\par\rndstring{\stringC}

\end{document}

相关内容