gpt4 book ai didi

r - 在 R 中包含 ASCII 艺术

转载 作者:行者123 更新时间:2023-12-04 10:46:23 25 4
gpt4 key购买 nike

我正在编写一个小程序,想知道是否有办法在 R 中包含 ASCII 艺术。我在 python 中寻找等效的三个引号( """''' )。

我尝试使用 catprint没有成功。

最佳答案

不幸的是,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 //_// ___/
\_)

关于r - 在 R 中包含 ASCII 艺术,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33628744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com