html - 使用混合字符编码读取 R 中的文件

标签 html r character-encoding

我正在尝试从主要以 UTF-8 编码(并声明 <meta charset="utf-8"> )但有一些其他编码(我认为是 Windows-1252 或 ISO 8859-1)的 HTML 页面中将表格读入 R . Here's an example.我希望所有内容都正确解码为 R 数据帧。 XML::readHTMLTable需要 encoding参数,但似乎不允许尝试多种编码。

那么,在 R 中,如何为输入文件的每一行尝试多种编码?在 Python 3 中,我会做类似的事情:

with open('file', 'rb') as o:
    for line in o:
        try:
            line = line.decode('UTF-8')
        except UnicodeDecodeError:
            line = line.decode('Windows-1252')

最佳答案

似乎确实有用于猜测字符编码的 R 库函数,例如 stringi::stri_enc_detect,但如果可能的话,最好使用更简单的确定性方法来尝试一组固定的编码命令。看起来最好的方法是利用以下事实:当 iconv 无法转换字符串时,它会返回 NA

linewise.decode = function(path)
    sapply(readLines(path), USE.NAMES = F, function(line) {
        if (validUTF8(line))
            return(line)
        l2 = iconv(line, "Windows-1252", "UTF-8")
        if (!is.na(l2))
            return(l2)
        l2 = iconv(line, "Shift-JIS", "UTF-8")
        if (!is.na(l2))
            return(l2)
        stop("Encoding not detected")
    })

如果你创建一个测试文件

$ python3 -c 'with open("inptest", "wb") as o: o.write(b"This line is ASCII\n" + "This line is UTF-8: I like π\n".encode("UTF-8") + "This line is Windows-1252: Müller\n".encode("Windows-1252") + "This line is Shift-JIS: ハローワールド\n".encode("Shift-JIS"))'

然后 linewise.decode("inptest") 确实返回了

[1] "This line is ASCII"                    
[2] "This line is UTF-8: I like π"          
[3] "This line is Windows-1252: Müller"     
[4] "This line is Shift-JIS: ハローワールド"

要将 linewise.decodeXML::readHTMLTable 一起使用,只需说类似 XML::readHTMLTable(linewise.decode("http://example .com")).

关于html - 使用混合字符编码读取 R 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56429901/

相关文章:

php - CSS/HTML/PHP 显示交替数组列表(Google Chrome 扩展)

javascript - 从javascript调用actionscript 3函数,addCallback不起作用

r - 如何将数据框列转换为数字类型?

r - 在 R 中创建一个非常大的稀疏矩阵

python - 具有不属于任何 ascii 超集的字符的消息的可测试性(例如 : JIS X 0208)?

java - 如何从网站获取非拉丁字符?

html - 使用 CSS/Angular JS 固定列和标题

jquery - 识别第一行的最后一个 flexbox 和最后一行的第一个 flexbox

MySQL - 显示特定连接 ID 的状态详细信息

r - 为什么 is.na() 改变它的参数?