Re: [問題] table問題(網頁編碼)

看板R_Language作者 (天)時間8年前 (2016/06/06 16:23), 8年前編輯推噓1(100)
留言1則, 1人參與, 最新討論串4/4 (看更多)
※ 引述《vicror84 (阿汘)》之銘言: : ※ 引述《celestialgod (天)》之銘言: : : 我不知道網頁的header跟內文的關係 : : 我看charset是big5,不過我實際讀表格的資料,還是要用UTF8 : : 所以我抓content的時候用big5是正常的,再用read_html with encoding utf8 : : 之後再把utf8轉回去big5 (windows才要轉,mac, linux不用stri_conv那段) : : 之後就可以看到正常的表格內容了 : : library(httr) : : library(pipeR) : : library(xml2) : : library(stringi) : : library(stringr) : : tableContent <- GET("http://depart.femh.org.tw/HMC/wholebody.html") %>>% : : content("text", encoding = "BIG5") %>>% read_html("UTF-8") %>>% : : xml_find_all("//tr/td/table/tbody/tr") %>>% lapply(function(x){ : : output_text <- xml_find_all(x, "td") %>>% xml_text %>>% : : stri_conv(from = "UTF-8", to = "Big5") %>>% str_replace_all("\\s", "") : : if (length(output_text) >= 9 && length(output_text) <= 11) : : { : : return(c(rep("", 12-length(output_text)), output_text)) : : } else if (length(output_text) == 8) : : { : : return(c(output_text[1:4], unlist(rbind(output_text[5:8], rep("", 4))))) : : } else : : { : : return(output_text) : : } : : }) %>>% do.call(what = rbind) : : 結果截圖: : : http://i.imgur.com/eDG4uEY.png
: : 函數說明可以往前翻我的文章,某一篇(#1N9lFXFI (R_Language))下面有一些說明 : : 不懂再回文發問吧 : : #那串的用法:http://evolutionbrain.blogspot.tw/2015/08/ptt.html : 因為我是新手剛學R,看不太懂 str_replace_all("\\s", "") 這段程式, : 還有, str_replace_all(string, pattern, replacement): http://www.inside-r.org/packages/cran/stringr/docs/str_replace_all 把string中符合pattern的字串置換成replacement的字串 例如:str_replace_all("aa bb cc", "\\s", "") "\\s"是regexp裡的空白,""就是零長度的字串,所以置換後就會變成 "aabbcc" %>>% 部分可以參考在板上/magrittr,有一篇簡單的教學文,看%>%部分 我這裡只有一個地方用到%>>%的特色 (do.call(what = rbind)這裡用到而已) : if (length(output_text) >= 9 && length(output_text) <= 11) : { : return(c(rep("", 12-length(output_text)), output_text)) : } else if (length(output_text) == 8) : { : return(c(output_text[1:4], unlist(rbind(output_text[5:8], rep("", 4)))) : } else : { : return(output_text) : } : }) %>>% do.call(what = rbind) : 尤其是那些數字,不太懂他們代表什麼意思,如果逐一註解更好,不方便的話沒有關係 數字是因為網頁的表格有跨欄位的問題,所以他不見得都會抓滿12欄 所以你需要自己手動去補成12欄,我只是做這樣的事情而已 因此,才會在你下一篇回答說那個表格處理請參考我下一篇 也就是這個部分,自己抓出每一列之後,做補滿或是調整空位的部分 這個可能對R新手比較困難一點,但是沒有現成的函數可以直接讀跨欄的欄位 如果只會用XML的readHTMLTable,就只會出現都靠左的情況,剩下都補入"" 這個就只能自己慢慢位移了 逐一註解就不做了,這裡只是一個概念,你需要自己動手去把table抓下來 看看抓下來的每一列長怎樣,然後程式裡對應處理為何 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.109.74.87 ※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1465201420.A.0D2.html ※ 編輯: celestialgod (140.109.74.87), 06/06/2016 16:26:20

06/07 22:47, , 1F
謝謝你~~ 這語言真得很難!!
06/07 22:47, 1F
文章代碼(AID): #1NLJCC3I (R_Language)
文章代碼(AID): #1NLJCC3I (R_Language)