我在 Tikz 中看到,除非我误解了,否则可以从一个键分配和检索多个属性。pgfkeys 文档始终提到要设置或获取的一对 key=value,但从未提到同一键的多个值。假设我为“State”定义了键,并希望将“state_name”、“capital”和population 分配为属性。然后我想使用键检索州的名称或人口(例如 AZ)。以下是开始的示例代码:
\documentclass[12pt,twoside]{article}
\RequirePackage{filecontents}% write the data file
\usepackage{pgfkeys}
\begin{filecontents}{states.csv}
AZ = { Arizona,Phoenix, 6931071}
CA = { California,Sacramento, 39250017}
FL = { Florida,Tallahassee, 20612439}
GA = { Georgia,Atlanta, 10310371}
MS = { Massachusetts,Boston, 6811779}
NY = { New York,Albany, 19745289}
TX = { Texas,Austin, 27862596}
\end{filecontents}
% BEGIN Read US States Definitions
\pgfkeys{/state/.is family, state,
% allow arbitrary unknown keys and set with \pgfkeyssetvalue
.unknown/.code={\pgfkeyssetvalue{\pgfkeyscurrentpath/\pgfkeyscurrentname}{#1}},
}
\newcommand\printstate[1]{% print the key if it is defined and ???Otherwise
\pgfkeysifdefined{/state/#1}{\pgfkeysvalueof{/state/#1}}{???}%
}
\newcommand\AddState[1]{\expandafter\pgfkeys\expandafter{/state, #1}}
\newread\statefile% file handler
\def\apar{\par}% \ifx\par won't work but \ifx\apar will
\newcommand\ReadStates[1]{% read file into [\pgfkeys{/state}
\openin\statefile=#1% open file for reading
\loop\unless\ifeof\statefile% loop until end of file
\read\statefile to \stateline% read line from file
\ifx\stateline\apar% test for \par
\else%
\ifx\stateline\empty\relax% skip over empty lines/comments
\else\expandafter\AddState\expandafter{\stateline}%
\fi%
\fi%
\repeat% end of file reading loop
\closein\statefile% close input file
}
\ReadStates{states.csv}% read the file
% END Read US States Definitions
\begin{document}
Hello:
\printstate{TX}
\\
\\ How to print The capital of Texas is "Austin" and
\\ total population is "27862596"
\\ Using "properties" of the key AZ?
\\ Prefer to use pgfkeys with out using packages to split the content of the value of the key
\end{document}
答案1
您可以使用处理程序为按键代码指定任意参数模式/.code args
。例如,.unknown
像这样定义按键处理程序:
.unknown/.code args={#1,#2,#3}{ % Format is <name>,<capital>,<population>
\pgfkeyssetvalue{\pgfkeyscurrentpath/\pgfkeyscurrentname/name}{#1}
\pgfkeyssetvalue{\pgfkeyscurrentpath/\pgfkeyscurrentname/capital}{#2}
\pgfkeyssetvalue{\pgfkeyscurrentpath/\pgfkeyscurrentname/population}{#3}
}
然后您可以/state/<NAME>/<field>
像这样使用定义的键:
The capital of \pgfkeys{/state/TX/name} is \pgfkeys{/state/TX/capital}
and total population is \pgfkeys{/state/TX/population}.