【问题标题】:add ' to front of string from vector将 ' 添加到来自向量的字符串的前面
【发布时间】:2014-08-04 13:05:16
【问题描述】:

我需要将 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---',(apostrophe - comma)。我需要把'(撇号)放在开头,不知道该怎么做。我尝试将 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编写。

【问题讨论】:

    标签: php regex r vector


    【解决方案1】:

    您可以稍微简化提取(也许这会处理您的撇号等?)

    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.'"   
    

    【讨论】:

    • 这很好地简化了提取,但不幸的是,它不能帮助我准备最终输出。但是谢谢你,我看到我在提取文本方面做得很辛苦。
    • 我想我可以使用 cat 和 paste 做一些事情,但仍然无法将其输出: cat( paste('"', out, '",', "\n", sep=" "))
    • 也许你想要head(paste0("'", out, "'"))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-18
    • 2022-08-07
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多