Latex 相當於 DECODE(檢查文字並分配數字)

Latex 相當於 DECODE(檢查文字並分配數字)

我的 CSV 檔案中有四個可能的句子。例如:這裡第 1 句,再加一句,再加一句,最後一句。

乳膠;如果存在“這裡的句子 1”,我想列印 1。類似 SQL 中的 DECODE。您能指出我可以學習類似功能的網址嗎?

問候,

答案1

由於您專門尋找 SQL 類型功能,因此我建議您探索一下datatool包裹。 MWE 讀取 CSV 文件MyData.csv,然後搜尋「另外一句話」和「另外三個句子」:

在此輸入影像描述

筆記:

  • filecontents套餐 用於設定要為此測試用例讀取的檔案。在您的實際用例中不需要它。
  • 我已經newtoggle用過etoolbox包裹因為我比較喜歡那種文法而不是\newif文法。但是,如果您不想包含額外的包,則可以非常簡單地對其進行調整以使用\newif其他一些條件方法
  • 如果這是您想要的所有功能,請將“找到它”文字變更為“1”(根據問題),或調整那裡的程式碼以執行其他操作。

代碼:

\documentclass{article}
\usepackage{datatool}
\usepackage{xstring}
\usepackage{etoolbox}

%\usepackage{filecontents}% <-- Commented out to prevent overwriting MyData.csv
\begin{filecontents*}{MyData.csv}
    sentence 1 here, 
    one more sentence, 
    one more sentence added, 
    last sentence,
\end{filecontents*}


\newtoggle{FoundInDB}
\newcommand*{\CheckIfInDB}[4]{%
    % #1 = database
    % #2 = string to chek
    % #3 = code to execute if string is found
    % #4 = code to execute if string is NOT found
    \global\togglefalse{FoundInDB}%
    \DTLforeach{#1}{%
         \CurrentSentence=Sentence%
    }{%
         \IfStrEq{\CurrentSentence}{#2}{%
             %% Found string -- we are done
             \global\toggletrue{FoundInDB}%
             \dtlbreak% No point in searching rest of file
         }{%
             % Still haven't found what we are looking for :-(
         }%
    }%
    \iftoggle{FoundInDB}{#3}{#4}%
}%


\begin{document}
\DTLloaddb[noheader,keys={Sentence}]{myDB}{MyData.csv}

\CheckIfInDB{myDB}{one more sentence}{Found it}{Not Found!}

\CheckIfInDB{myDB}{three more sentences}{Found it}{Not Found!}

\end{document} 

答案2

如果我理解正確的話,您想檢查 CSV 文件中的一行並根據這句話分配一個數字。

您可以使用 R 和 sweave 檔案簡單地實現此目的(它們基本上是具有 R 語言功能的 LaTeX 檔案。請記得將 knit 套件新增至 R studio 中。

所以你像普通乳膠一樣開始文件,然後在\begin{document} 你寫下以下塊之後

<<echo=false>>=
Data<-read.csv("file.path.here")
sapply(Data, function(x){
if(x=="sentence 1 here"){
    return(1)
} elseif(x=="sentence2"){
    return(2)
}else{
    return(0)
}
@

相關內容