text2paddle.py 3.2 KB
Newer Older
F
frankwhzhang 已提交
1 2 3 4
import sys
import six
import collections
import os
Z
zhang wenhui 已提交
5
import sys
6
import io
Z
zhang wenhui 已提交
7 8 9 10
if six.PY2:
    reload(sys)
    sys.setdefaultencoding('utf-8')

F
frankwhzhang 已提交
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33

def word_count(input_file, word_freq=None):
    """
    compute word count from corpus
    """
    if word_freq is None:
        word_freq = collections.defaultdict(int)

    for l in input_file:
        for w in l.strip().split():
            word_freq[w] += 1

    return word_freq


def build_dict(min_word_freq=0, train_dir="", test_dir=""):
    """
    Build a word dictionary from the corpus,  Keys of the dictionary are words,
    and values are zero-based IDs of these words.
    """
    word_freq = collections.defaultdict(int)
    files = os.listdir(train_dir)
    for fi in files:
34
        with io.open(os.path.join(train_dir, fi), "r") as f:
F
frankwhzhang 已提交
35 36 37
            word_freq = word_count(f, word_freq)
    files = os.listdir(test_dir)
    for fi in files:
38
        with io.open(os.path.join(test_dir, fi), "r") as f:
F
frankwhzhang 已提交
39 40 41 42 43 44 45 46 47
            word_freq = word_count(f, word_freq)

    word_freq = [x for x in six.iteritems(word_freq) if x[1] > min_word_freq]
    word_freq_sorted = sorted(word_freq, key=lambda x: (-x[1], x[0]))
    words, _ = list(zip(*word_freq_sorted))
    word_idx = dict(list(zip(words, six.moves.range(len(words)))))
    return word_idx


Z
zhang wenhui 已提交
48 49
def write_paddle(word_idx, train_dir, test_dir, output_train_dir,
                 output_test_dir):
F
frankwhzhang 已提交
50 51 52 53
    files = os.listdir(train_dir)
    if not os.path.exists(output_train_dir):
        os.mkdir(output_train_dir)
    for fi in files:
54 55
        with io.open(os.path.join(train_dir, fi), "r") as f:
            with io.open(os.path.join(output_train_dir, fi), "w") as wf:
F
frankwhzhang 已提交
56 57 58 59
                for l in f:
                    l = l.strip().split()
                    l = [word_idx.get(w) for w in l]
                    for w in l:
60 61
                        wf.write(str2file(str(w) + " "))
                    wf.write(str2file("\n"))
F
frankwhzhang 已提交
62 63 64 65 66

    files = os.listdir(test_dir)
    if not os.path.exists(output_test_dir):
        os.mkdir(output_test_dir)
    for fi in files:
67 68 69 70
        with io.open(os.path.join(test_dir, fi), "r", encoding='utf-8') as f:
            with io.open(
                    os.path.join(output_test_dir, fi), "w",
                    encoding='utf-8') as wf:
F
frankwhzhang 已提交
71 72 73 74
                for l in f:
                    l = l.strip().split()
                    l = [word_idx.get(w) for w in l]
                    for w in l:
75 76 77 78 79 80 81 82 83
                        wf.write(str2file(str(w) + " "))
                    wf.write(str2file("\n"))


def str2file(str):
    if six.PY2:
        return str.decode("utf-8")
    else:
        return str
F
frankwhzhang 已提交
84

Z
zhang wenhui 已提交
85 86 87

def text2paddle(train_dir, test_dir, output_train_dir, output_test_dir,
                output_vocab):
F
frankwhzhang 已提交
88
    vocab = build_dict(0, train_dir, test_dir)
89 90 91
    print("vocab size:", str(len(vocab)))
    with io.open(output_vocab, "w", encoding='utf-8') as wf:
        wf.write(str2file(str(len(vocab)) + "\n"))
F
frankwhzhang 已提交
92 93 94 95 96 97 98 99
    write_paddle(vocab, train_dir, test_dir, output_train_dir, output_test_dir)


train_dir = sys.argv[1]
test_dir = sys.argv[2]
output_train_dir = sys.argv[3]
output_test_dir = sys.argv[4]
output_vocab = sys.argv[5]
Z
zhang wenhui 已提交
100 101
text2paddle(train_dir, test_dir, output_train_dir, output_test_dir,
            output_vocab)