File size: 1,777 Bytes
981fedd
 
 
 
 
 
 
c3e06e3
981fedd
 
c3e06e3
981fedd
 
c3e06e3
981fedd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json


def main():
        
    json_array = []

    with open('resources/all_titles.txt', encoding="utf-8") as title_file:
        all_titles = title_file.read().splitlines()
    
    with open('resources/cleaned_merged_fairy_tales_without_eos.txt', encoding='UTF-8') as stories_file:
        content = stories_file.read().splitlines()

    with open('resources/lines.txt', encoding="utf-8") as lines_file:
        all_lines = lines_file.read().splitlines()


    print("Now converting the .txt file to a .json ...")
    print("Please wait ...")


    for idx in range(len(all_titles)):

        try:

            json_item = {}

            title1 = all_titles[idx]
            json_item["Title"] = title1

            start_idx = int(all_lines[idx])
            end_idx = int(all_lines[idx+1])

            content_list = content[start_idx : end_idx-1]
            json_item["Content"] = " ".join([str(item) for item in content_list])
            json_array.append(json_item)

        except:  # except IndexError: list index out of range
    
            pass

    result = remove_duplicate_items(json_array)

    with open('stories.json', "w", encoding="utf-8") as myfile2:
        myfile2.write(json.dumps(result, ensure_ascii=False, indent=4))

    print("Completed. Please find the stories in stories.json.")


def remove_duplicate_items(json_list):

    # keep a dictionary of key = title, value = count to see how many times the same story appears,
    # then remove duplicates

    result_json = []
    keys = []

    for idx in range(len(json_list)):
        if json_list[idx]['Title'] in keys:
            pass
        else:
            result_json.append(json_list[idx])
            keys.append(json_list[idx]['Title'])
    
    return result_json


main()