python - 从文件生成 block

标签 python generator

我有一个 JSON 文件,想编写一个函数来返回文件中下 10 个对象 的列表。我从一个类 FileProcessor 和方法 get_row() 开始,它返回一个生成器,该生成器从文件中生成单个 JSON 对象。另一种方法 get_chunk() 应该返回接下来的 10 个对象。

这是我目前所拥有的:

class FileProcessor(object):

    def __init__(self, filename):
        self.FILENAME = filename

    def get_row(self):
        with open( os.path.join('path/to/file', self.FILENAME), 'r') as f:
            for i in f:
                yield json.loads(i)

    def get_chunk(self):
        pass

我试过这样,但它每次只返回前 10 行。

    def get_chunk(self):
        chunk = []
        consumer = self.consume()
        for i in self.get_row():
            chunk.append(i)
        return chunk     

那么get_chunk()的正确写法是什么?

最佳答案

这是一个简单的生成器,它从另一个生成器获取值并将它们放入列表中。它应该与您的 FileProcessor.get_row 方法一起使用。

def count(n):
    for v in range(n):
        yield str(v)

def chunks(it, n):
    while True:
        yield [next(it) for _ in range(n)]

for u in chunks(count(100), 12):
    print(u)

输出

['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11']
['12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23']
['24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35']
['36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47']
['48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59']
['60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71']
['72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83']
['84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95']

请注意,这只会产生完整的 block 。如果这是一个问题,您可以这样做:

def chunks(it, n):
    while True:
        chunk = []
        for _ in range(n):
            try:
                chunk.append(next(it))
            except StopIteration: 
                yield chunk
                return
        yield chunk

将打印

['96', '97', '98', '99']

在上一个输出之后。


更好的方法是使用 itertools.islice ,它将处理部分最终 block :

from itertools import islice

def chunks(it, n):
    while True:
        a = list(islice(it, n))
        if not a:
            return
        yield a

感谢Antti Haapala提醒我 islice。 :)

关于python - 从文件生成 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40500086/

相关文章:

python - 使用 BeautifulSoup 抓取表格

python - 从字符串中删除小写子字符串的快速方法?

python - 可以在 Python 中重置迭代器吗?

python - 从 python 中的列表创建生成器表达式

python - 我在 django 中的评论表单不起作用?它既不向数据库发送数据也不显示这些数据?

python - Celery + RabbitMQ - 使用 Celery 进行简单消息传递

python - 为什么 keras 模型编译但 fit_generator 命令抛出 'model not compiled runtime error' ?

Python语法错误: ("' return' with argument inside generator",)

python - 是否可以恢复迭代器并可以分配其值/状态?

javascript - 如何在 n 秒后停用 MutationObserver?