定时器和XML文件处理

2024-04-18 23:14:01 发布

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

我必须处理一个大的XML文档,为此我有几个数据清理和操作任务要做。你知道吗

下面的基本代码使用xml.etree.ElementTree。 由于文件非常大(大约2Gb),我希望能够定期打印tagCounts累加器变量的值。你知道吗

使用ElementTree每3分钟打印self.tagCounts的内容来实现计时器的最干净的方法是什么?

谢谢

import xml.etree.ElementTree as ET
import pprint

class TagCounter:
    def __init__(self):
        self.tagCounts = {}

    def start(self, tag, attrib):
        if tag in self.tagCounts:
            self.tagCounts[tag] += 1
        else:
            self.tagCounts[tag] = 1        

    def end(self, tag):
        pass

    def data(self, data):
        pass

    def close(self):
        return self.tagCounts

def count_tags(filename):
    parser = ET.XMLParser(target = TagCounter())
    with open(filename, mode='r') as f:
        for line in f:
            parser.feed(line)
    t = parser.close()
    return t

if __name__ == "__main__":
    tags = count_tags("file.osm")
    pprint.pprint(tags)

Tags: importselfparserifdefastagtags
1条回答
网友
1楼 · 发布于 2024-04-18 23:14:01

What is the cleanest way to implement a timer using ElementTree printing every 3 minutes the content of self.tagCounts?

我不明白ElementTree与实现计时器有什么关系:

class TagCounter:
    def __init__(self):
        self.tag_counts = {}
        self.cancel_print = call_repeatedly(3*60, pprint.pprint, self.tag_counts)

    # ...

    def close(self):
        self.cancel_print()
        return self.tag_counts

其中^{} calls ^{} every ^{} seconds。你知道吗

相关问题 更多 >