2

我已经将该strwrap函数包装成strWrap接受来自剪贴板的文本以及自动写入剪贴板的功能。在此我假设 mac 的系统名称是 Darwin。此功能适用于 Windows 机器(抱歉,Linux 有太多的变化使其可行,并且大多数使用此功能的软件包的人无论如何都不是 linux 用户)。

我在psych包的read.clipboard函数之后建模了我的函数。不幸的是,我请一些人在talkstats.com上试用它,他们有一个 mac,但它不起作用。我怎样才能使它也适用于mac?根据this SO post ,我的代码似乎也适用于mac用户。

如果这按预期工作,它应该能够从 mac 用户的剪贴板读取并在完成后写入剪贴板。我#在最后用 a 标记了 mac 特定行,以便于理解问题

strWrap <-
function(text = "clipboard", width = 70) {
    if (text == "clipboard") {
        if (Sys.info()["sysname"] == "Darwin") {        #
            text <- paste(pipe("pbpaste"), collapse=" ")#
        }                                               #
        if (Sys.info()["sysname"] == "Windows") {
            text <- paste(readClipboard(), collapse=" ")
        }
    } 
    x <- gsub("\\s+", " ", gsub("\n|\t", " ", text))
    x <- strwrap(x, width = width)
    if (Sys.info()["sysname"] == "Windows") {
        writeClipboard(x, format = 1)
    }
    if (Sys.info()["sysname"] == "Darwin") {           #
        j <- pipe("pbcopy", "w")                       #
        cat(x, file = j)                               #
        close(j)                                       # 
    }                                                  #
    writeLines(x)
}

X <- "Two households, both alike in dignity, In fair Verona, where we lay
our scene, From ancient grudge break to new mutiny, Where civil blood
makes civil hands unclean. From forth the fatal loins of these two
foes A pair of star-cross'd lovers take their life; Whose
misadventured piteous overthrows Do with their death bury their
parents' strife. The fearful passage of their death-mark'd love, And
the continuance of their parents' rage, Which, but their children's
end, nought could remove, Is now the two hours' traffic of our stage;
The which if you with patient ears attend"

strWrap(X, 70)
4

1 回答 1

3

pipe返回一个连接对象。您需要从连接中读取。例如

pcon <- pipe("pbpaste")
text <- paste(scan(pcon, what="character", quiet=TRUE), collapse=" ")
close(pcon)

这适用于我的mac。

于 2012-08-02T22:44:24.977 回答