elatelttat / separate-stories.py
raksha-rehal's picture
Update separate-stories.py
c3e06e3 verified
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()