topic_materialization.py 1.3 KB
Newer Older
W
wenquan wu 已提交
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# Copyright (c) 2019 Baidu.com, Inc. All Rights Reserved
#
################################################################################
"""
File: topic_materialization.py
"""

from __future__ import print_function

import sys
import json

reload(sys)
sys.setdefaultencoding('utf8')


def topic_materialization(input_file, output_file, topic_file):
    """
    topic_materialization
    """
    inputs = [line.strip() for line in open(input_file, 'r')]
    topics = [line.strip() for line in open(topic_file, 'r')]

    assert len(inputs) == len(topics)

    fout = open(output_file, 'w')
    for i, text in enumerate(inputs):
        topic_dict = json.loads(topics[i], encoding="utf-8")
        topic_list = sorted(topic_dict.items(), key=lambda item: len(item[1]), reverse=True)
        for key, value in topic_list:
            text = text.replace(key, value)
        fout.write(text + "\n")

    fout.close()


def main():
    """
    main
    """
    topic_materialization(sys.argv[1],
                          sys.argv[2],
                          sys.argv[3])


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print("\nExited from the program ealier!")