我正在用Rmarkdown写一篇论文(通过LaTeX导出为PDF),我需要计算正文中的单词数。对于LaTeX文档,我使用命令行中的texcount
,使用tex文档中的以下标记指定要从字数排除的部分:
%TC:ignore
The part that is to be ignored (e.g., Appendix)
%TC:endignore
如何在我的Rmd文件中包含LaTeX注释,以避免每次重新生成时在tex文件中手动添加%TC
行?
这是我的MWE .Rmd
:
---
output:
pdf_document:
keep_tex: yes
---
Words that I want to count.
<!-- TC:ignore -->
Words that I want to exclude but cannot,
because the comments do not appear in the `.tex` file.
<!-- TC:endignore -->
%TC:ignore
Other words that I want to exclude but this does not work either
because `%` is not interpreted as \LaTeX comment.
%TC:endignore
#%TC:ignore
Another attempt; it does not work because `#` is for sections,
not comments.
#%TC:endignore
一旦我编织.Rmd文件并输出.tex文件,我就输入:
texcount MWE.tex
答案应该是6个字。 谢谢!
更新1:
在Twitter上,@ thesoudi建议使用RStudio加载项(WordCountAddIn)来计算我的Rmd文档中的单词。该加载项位于https://github.com/benmarwick/wordcountaddin。但是,这不是自动化的,并且仍然存在一些指向和点击。
更新2:
另一种解决方案是
使用特定表达式来识别LaTeX评论应该是什么,例如: LATEXCOMMENT%TC:ignore
文件中的.Rmd
,
有一个脚本可自动删除生成的LATEXCOMMENT
文档中的.tex
个表达式(例如sed
)
答案 0 :(得分:0)
我们实际上只是直接使用.Rmd文件,而不是对输出的LaTex文件进行字数统计。
此代码与您提到的wordcountaddin的方法类似,但标记<!---TC:ignore--->
和<!---TC:endignore--->
之间的任何文字都不会包含在计数中:
library(stringr)
library(tidyverse)
RmdWords <- function(file) {
# Creates a string of text
file_string <- file %>%
readLines() %>%
paste0(collapse = " ") %>%
# Remove YAML header
str_replace_all("^<--- .*?--- ", "") %>%
str_replace_all("^--- .*?--- ", "") %>%
# Remove code
str_replace_all("```.*?```", "") %>%
str_replace_all("`.*?`", "") %>%
# Remove LaTeX
str_replace_all("[^\\\\]\\$\\$.*?[^\\\\]\\$\\$", "") %>%
str_replace_all("[^\\\\]\\$.*?[^\\\\]\\$", "") %>%
# Deletes text between tags
str_replace_all("TC:ignore.*?TC:endignore", "") %>%
str_replace_all("[[:punct:]]", " ") %>%
str_replace_all(" ", "") %>%
str_replace_all("<", "") %>%
str_replace_all(">", "")
# Save several different results
word_count <- str_count(file_string, "\\S+")
char_count <- str_replace_all(string = file_string, " ", "") %>% str_count()
return(list(num_words = word_count, num_char = char_count, word_list = file_string))
}
该函数返回列表中的三个项目:
如果要在编译的报告中显示结果,可以按如下方式内联编写r代码:
```{r}
words <- RmdWords("MWE.Rmd")
```
There are seven words with 34 characters.
<!-- TC:ignore -->
Words that I want to exclude but cannot,
because the comments do not appear in the `.tex` file.
<!-- TC:endignore -->
<!-- TC:ignore -->
Word Count: `r words$num_words` \newline
Character Count: `r words$num_char`
<!-- TC:endignore -->
注意:部分原始脚本改编自http://www.questionflow.org/2017/10/13/how-to-scrape-pdf-and-rmd-to-get-inspiration/