【发布时间】:2016-02-11 06:10:02
【问题描述】:
我正在编写一个小程序,想知道是否有办法在 R 中包含 ASCII 艺术。我在 python 中寻找相当于三个引号(""" 或 ''')的方法。
我尝试使用cat 或print 没有成功。
【问题讨论】:
我正在编写一个小程序,想知道是否有办法在 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
网址 - 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)
如果没有连接到网络,您可以设置自己的服务器。 Read more here
感谢@johnnyaboh 提供这项令人惊叹的服务
【讨论】:
试试 cat 函数,这样的东西应该可以工作:
cat(" \"\"\" ")
【讨论】: