且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过python从行到行yelp数据集读取

更新时间:2023-12-06 17:02:40

如果每行是JSON:

revu=[]
with open("review.json", 'r',encoding="utf8") as f:
    # expensive statement, depending on your filesize this might
    # let you run out of memory
    revu = [json.loads(s) for s in f.readlines()[1400001:1450000]]

如果您在/etc/passwd文件中执行此操作,则很容易测试(当然没有json,因此可以忽略)

if you do it on the /etc/passwd file it is easy to test (no json of course, so that is left out)

revu = []
with open("/etc/passwd", 'r') as f:
    # expensive statement
    revu = [s for s in f.readlines()[5:10]]

print(revu)  # gives entry 5 to 10

或者您遍历所有行,从而避免出现内存问题:

Or you iterate over all lines, saving you from memory issues:

revu = []
with open("...", 'r') as f:
    for i, line in enumerate(f):
        if i >= 1400001 and i <= 1450000:
            revu.append(json.loads(line))

# process revu   

至CSV ...

import pandas as pd
import json

def mylines(filename, _from, _to):
    with open(filename, encoding="utf8") as f:
        for i, line in enumerate(f):
            if i >= _from and i <= _to:
                yield json.loads(line)

df = pd.DataFrame([r for r in mylines("review.json", 1400001, 1450000)])
df.to_csv("/tmp/whatever.csv")