我正在编写一个小程序,想知道是否有一种方法可以在R中包含ASCII艺术。我在寻找Python中三引号(
"""
或'''
)的等效物。
我尝试使用cat
或print
,但没有成功。
不幸的是,R只能使用单引号或双引号来表示文字字符串,这使得表示ASCII艺术变得很棘手;但是,您可以按照以下步骤获得艺术的文本表示形式,该文本表示形式可以使用R的cat
函数输出。
1) 首先将您的艺术放入一个文本文件中:
# ascii_art.txt is our text file with the ascii art
# For test purposes we use the output of say("Hello") from cowsay package
# and put that in ascii_art.txt
library(cowsay)
writeLines(capture.output(say("Hello"), type = "message"), con = "ascii_art.txt")
2) 然后读入文件并使用dput
:
art <- readLines("ascii_art.txt")
dput(art)
它会产生这个输出:
c("", " -------------- ", "Hello ", " --------------", " \\",
" \\", " \\", " |\\___/|", " ==) ^Y^ (==",
" \\ ^ /", " )=*=(", " / \\",
" | |", " /| | | |\\", " \\| | |_|/\\",
" jgs //_// ___/", " \\_)", " ")
3) 最后在您的代码中编写:
art <- # copy the output of `dput` here
所以你的代码应该包含这个:
art <-
c("", " -------------- ", "Hello ", " --------------", " \\",
" \\", " \\", " |\\___/|", " ==) ^Y^ (==",
" \\ ^ /", " )=*=(", " / \\",
" | |", " /| | | |\\", " \\| | |_|/\\",
" jgs //_// ___/", " \\_)", " ")
4) 现在如果我们简单地使用cat
命令输出art
变量,则会显示出来:
> cat(art, sep = "\n")
--------------
Hello
--------------
\
\
\
|\___/|
==) ^Y^ (==
\ ^ /
)=*=(
/ \
| |
/| | | |\
\| | |_|/\
jgs //_// ___/
\_)
这是几年后的一个新增。在 R 4.0 中,有一种新的语法可以使这个过程更加容易操作。请参见?Quotes
。
例如:Raw character constants are also available using a syntax similar to the one used in C++: ‘r"(...)"’ with ‘...’ any character sequence, except that it must not contain the closing sequence ‘)"’. The delimiter pairs ‘[]’ and ‘{}’ can also be used, and ‘R’ can be used in place of ‘r’. For additional flexibility, a number of dashes can be placed between the opening quote and the opening delimiter, as long as the same number of dashes appear between the closing delimiter and the closing quote.
hello <- r"{
--------------
Hello
--------------
\
\
\
|\___/|
==) ^Y^ (==
\ ^ /
)=*=(
/ \
| |
/| | | |\
\| | |_|/\
jgs //_// ___/
\_)
}"
cat(hello)
提供:
--------------
Hello
--------------
\
\
\
|\___/|
==) ^Y^ (==
\ ^ /
)=*=(
/ \
| |
/| | | |\
\| | |_|/\
jgs //_// ___/
\_)
备选方案:使用API
URL - artii
步骤:
ascii_request <- httr::GET("http://artii.herokuapp.com/make?text=this_is_your_text&font=ascii___")
ascii_response <- httr::content(ascii_request,as = "text", encoding = "UTF-8")
cat(ascii_response)
如果没有连接到网络,可以设置自己的服务器。 在此处阅读更多
感谢@johnnyaboh搭建这个惊人的服务
尝试使用cat函数,类似这样的代码应该可以工作:
cat(" \"\"\" ")