【问题标题】:How to get byte offset in a file in python如何在python中获取文件中的字节偏移量
【发布时间】:2010-09-04 11:41:41
【问题描述】:

我正在使用 hadoop 和 python 创建一个倒排索引。 我想知道如何在 python 中包含行/单词的字节偏移量。 我需要这样的东西

hello hello.txt@1124

我需要制作完整倒排索引的位置。 请帮忙。

【问题讨论】:

    标签: python inverted-index


    【解决方案1】:

    像这样?

    file.tell()
    

    返回文件的当前位置,如 stdio 的 ftell()。

    http://docs.python.org/library/stdtypes.html#file-objects

    不幸的是,tell() 不起作用,因为 OP 使用的是标准输入而不是文件。但是围绕它构建一个包装器来提供你需要的东西并不难。

    class file_with_pos(object):
        def __init__(self, fp):
            self.fp = fp
            self.pos = 0
        def read(self, *args):
            data = self.fp.read(*args)
            self.pos += len(data)
            return data
        def tell(self):
            return self.pos
    

    那么你可以用这个代替:

    fp = file_with_pos(sys.stdin)
    

    【讨论】:

    • 在答案中添加了包装类。
    • 感谢您的回复...将尝试一下...但是,目前我已经实现了一个计数器变量来跟踪位置。它工作得很好,因为我只需要文件中的相对位置。
    • @Siddharth:Wai 建议的代码似乎与您的“当前”代码完全一样。除非您发布自己的代码并将其标记为 答案,否则请将 Wai 的答案标记为所选答案。
    猜你喜欢
    • 2014-04-03
    • 2012-11-30
    • 2016-12-27
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多