从向量中添加'到字符串的前面

时间:2014-06-13 21:57:36

标签: php regex r vector

我需要将html解析的结果打印到PHP数组中。我被困在最后一部分。

    library(XML)
    url ='http://www.brainyquote.com/quotes/authors/j/john_kenneth_galbraith.html'
    page <- htmlParse(url)
    quote <- xpathSApply(page, 
  "//text()[not(ancestor::script)][not(ancestor::style)][not(ancestor::noscript)][not(ancestor::form)]", 
  xmlValue)
    quote = quote[nchar(quote) > 50] # this removes all none quotes based on string length
quote = quote[1:(length(quote)-2)]  # this drops the last 
    out = paste(quote, collaspe= "', ") # how to get the ' at the front of the quote
    write(out, "quote.txt")

最后的代码最后有一个文本字符串--- quote here ---&#39;,(撇号 - 逗号)。我需要把#撇号(撇号)放在开头,不知道怎么做。我尝试使用r到json但是对我使用的简单php数组不起作用。这是这样的结构:

<?php
$quotes = array('quote goes here', 'quote goes here', 'final quote');
$rand = rand( 0, count($quotes)-1 );
echo $quotes[$rand];
?>

我不是真的使用PHP,但它只是在所有东西上运行所以我做这个随机引用制造商是简单的术语。我可以在javascript中重写并使用json数组。但我需要用javascript编写。

1 个答案:

答案 0 :(得分:0)

你可以稍微简化一下提取(也许这会照顾你的撇号等?)

library(XML)
url ='http://www.brainyquote.com/quotes/authors/j/john_kenneth_galbraith.html'
page <- htmlParse(url)
out <- sapply(page['//span[@class="bqQuoteLink"]/a'], xmlValue)
write(out, "quote.txt")

> head(paste0("'", out, "'"))
[1] "'The modern conservative is engaged in one of man's oldest exercises in moral philosophy; that is, the search for a superior moral justification for selfishness.'"                                                        
[2] "'Economics is extremely useful as a form of employment for economists.'"                                                                                                                                                   
[3] "'All of the great leaders have had one characteristic in common: it was the willingness to confront unequivocally the major anxiety of their people in their time. This, and not much else, is the essence of leadership.'"
[4] "'In economics, the majority is always wrong.'"                                                                                                                                                                             
[5] "'Faced with the choice between changing one's mind and proving that there is no need to do so, almost everyone gets busy on the proof.'"                                                                                   
[6] "'Under capitalism, man exploits man. Under communism, it's just the opposite.'"