不能阅读美国政府Python或R中的数据

2024-06-01 01:06:48 发布

您现在位置:Python中文网/ 问答频道 /正文

请检查一下档案资料USA GOV Sample Data

现在我想在R中读取这个文件,然后得到下面提到的错误

result = fromJSON(textFileName)
Error in fromJSON(textFileName) : unexpected character 'u'

当我想在Python中阅读它时,得到下面提到的错误

import json 
records = [json.loads(line) for line in open(path)]

--------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) codecs.charmap_decode(input,self.errors,decoding_table)[0] 24 25 class StreamWriter(Codec,codecs.StreamWriter): UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 4088: character maps to <undefined>

有人能帮我看一下这种文件吗。你知道吗


Tags: 文件injson错误linedecodecodecscharacter
2条回答

我在我的系统(windows/Rstudio/Jupyter)上也找不到OP提供的关于这个问题的代码。我四处挖掘,找到R的this,将其改编成这个例子:

library(jsonlite)
out <- lapply(readLines("usagov_bitly_data2013-05-17-1368817803"), fromJSON)
df<-data.frame(Reduce(rbind, out))

尽管我在R中得到的错误与你的不同。你知道吗

result = fromJSON("usagov_bitly_data2013-05-17-1368817803")
#Error in parse_con(txt, bigint_as_char) : parse error: trailing garbage
#           [ 34.730400, -86.586098 ] } { "a": "Mozilla\/5.0 (Windows N
#                     (right here)    ^

对于Python,正如juanpa所提到的,这似乎是一个编码问题。下面的代码适用于我。你知道吗

import json 
import os
path=os.path.abspath("usagov_bitly_data2013-05-17-1368817803")
print(path)
file = open(path, encoding="utf8")
records = [json.loads(line) for line in file]

R溶液:

library(jsonlite)

# if you have a local file
conn <- gzcon(file("usagov_bitly_data2013-05-17-1368817803.gz", "rb"))
# if you read it from URL
conn <- gzcon(url("http://1usagov.measuredvoice.com/bitly_archive/usagov_bitly_data2013-05-17-1368817803.gz"))

data <- stream_in(conn)

相关问题 更多 >