【发布时间】:2016-04-15 02:47:33
【问题描述】:
如何在 R 中证明文本的合理性?对齐我的意思是段落中的每一行的长度完全相同(就像您在开放式办公室或 excel 中对齐时一样)。我试图找到strwrap 和cat 的选项,但没有成功。
## Get some sample text example from wikipedia api
library(httr)
library(xml2)
name <- "Invictus"
url <- URLencode(sprintf("https://en.wikisource.org/w/api.php?action=parse&prop=text&page=%s&format=json", name))
res <- read_html(content(GET(url))$parse$text[[1]])
string <- iconv(xml_text(xml_find_all(res, "//p"), trim=TRUE), "latin1", "ASCII", sub=" ")[1:2]
(string <- trimws(gsub('\\n|\\s{3,}', ' ', paste(string, collapse=" "))))
# [1] "Out of the night that covers me, Black as the pit from pole to pole, I thank whatever gods may be For my unconquerable soul. In the fell clutch of circumstance I have not winced nor cried aloud. Under the bludgeonings of chance My head is bloody, but unbow'd. Beyond this place of wrath and tears Looms but the Horror of the shade, And yet the menace of the years Finds and shall find me unafraid. It matters not how strait the gate, How charged with punishments the scroll, I am the master of my fate: I am the captain of my soul."
使用上述功能的一些尝试
## Using these I can get left/right/center justified text but not
## justified like in other text editing programs or newspapers.
width <- 30
cat(paste(strwrap(string, width=width), collapse='\n'))
## Or with cat
tokens <- strsplit(string, '\\s+')[[1]] # tokenise to pass to cat
out <- capture.output(cat(tokens, fill=width, sep=" ")) # strings <= width chars
cat(paste(out, collapse='\n'))
【问题讨论】:
-
使用 TeX 渲染文本,例如通过 pandoc 或 tikzDevice 可能是你最好的选择
-
如果渲染成 HTML,你可以使用
<p style='text-align:justify;'>your text here</p>标签集。见w3schools.com/cssref/pr_text_text-align.asp。如果您尝试在控制台中执行此操作,我祝您好运,但怀疑有什么可以帮助您的。 -
这里有一些有用的信息:shiny.rstudio.com/articles/css.html。正如本杰明所说,你只需要在你的css中指定
text-align: justify。