说到Python,我还是个初学者,但我学校的一个项目需要我在这个reddit流行度数据集上执行分类算法。这些文件是巨大的.zst文件,可以在这里找到:https://files.pushshift.io/reddit/submissions/无论如何,我只是不确定如何将其提取到数据库中,因为到目前为止我们刚刚完成的作业使用了.csv数据集,我可以很容易地将其放入pandas数据框中。我偶然发现了一个不同的帖子,并尝试使用代码:
def transform_zst_file(self,infile):
zst_num_bytes = 2**22
lines_read = 0
dctx = zstd.ZstdDecompressor()
with dctx.stream_reader(infile) as reader:
previous_line = ""
while True:
chunk = reader.read(zst_num_bytes)
if not chunk:
break
string_data = chunk.decode('utf-8')
lines = string_data.split("\n")
for i, line in enumerate(lines[:-1]):
if i == 0:
line = previous_line + line
self.appendData(line, self.type)
lines_read += 1
if self.max_lines_to_read and lines_read >= self.max_lines_to_read:
return
previous_line = lines[-1]但我不完全确定如何将其放入pandas数据帧中,或者如果文件太大,则只将一定百分比的数据点放入数据帧中。任何帮助都将不胜感激!
下面的代码只在我每次尝试运行它时使我的计算机崩溃:
import zstandard as zstd
your_filename = "..."
with open(your_filename, "rb") as f:
data = f.read()
dctx = zstd.ZstdDecompressor()
decompressed = dctx.decompress(data)可能是因为文件太大了,有没有办法将文件中的一部分提取到pandas数据帧中呢?
发布于 2020-04-07 04:27:44
该文件已使用压缩库Zstandard (https://github.com/facebook/zstd)进行压缩。
对于您来说,最简单的方法可能是使用以下命令安装python-zstandard (https://pypi.org/project/zstandard/)
pip install zstandard然后在python脚本中运行类似于
import zstandard as zstd
your_filename = "..."
with open(your_filename, "rb") as f:
data = f.read()
dctx = zstd.ZstdDecompressor()
decompressed = dctx.decompress(data)现在,您可以直接使用解压缩的数据,也可以将其写入某个文件,然后将其加载到pandas。祝好运!
发布于 2021-10-18 07:02:21
我偶然发现了一个类似的由zst转储组成的Reddit数据集。为了迭代zst文件的内容,我使用了以下代码,您可以将其作为脚本运行:
import zstandard
import os
import json
import sys
from datetime import datetime
import logging.handlers
log = logging.getLogger("bot")
log.setLevel(logging.DEBUG)
log.addHandler(logging.StreamHandler())
def read_lines_zst(file_name):
with open(file_name, 'rb') as file_handle:
buffer = ''
reader = zstandard.ZstdDecompressor(max_window_size=2**31).stream_reader(file_handle)
while True:
chunk = reader.read(2**27).decode()
if not chunk:
break
lines = (buffer + chunk).split("\n")
for line in lines[:-1]:
yield line, file_handle.tell()
buffer = lines[-1]
reader.close()
if __name__ == "__main__":
file_path = sys.argv[1]
file_size = os.stat(file_path).st_size
file_lines = 0
file_bytes_processed = 0
created = None
field = "subreddit"
value = "wallstreetbets"
bad_lines = 0
try:
for line, file_bytes_processed in read_lines_zst(file_path):
try:
obj = json.loads(line)
created = datetime.utcfromtimestamp(int(obj['created_utc']))
temp = obj[field] == value
except (KeyError, json.JSONDecodeError) as err:
bad_lines += 1
file_lines += 1
if file_lines % 100000 == 0:
log.info(f"{created.strftime('%Y-%m-%d %H:%M:%S')} : {file_lines:,} : {bad_lines:,} : {(file_bytes_processed / file_size) * 100:.0f}%")
except Exception as err:
log.info(err)
log.info(f"Complete : {file_lines:,} : {bad_lines:,}")https://stackoverflow.com/questions/61067762
复制相似问题