Reputation: 331
I have a .txt which contains a list of codes:
1001
1002
1003
1004
1005
1006
1007
1008
0101
0102
0103
0104
0105
0106
and another file which contains the meaning of each code and has the following structure:
{
"more": false,
"classCode": "H0",
"className": "HS1992",
"minimumInputLength": 2,
"results": [{
"id": "ALL",
"text": "All HS1992 commodities",
"parent": "#"
},
{
"id": "TOTAL",
"text": "Total of all HS1992 commodities",
"parent": "#"
},
{
"id": "AG2",
"text": "AG2 - All 2-digit HS1992 commodities",
"parent": "#"
},
{
"id": "AG4",
"text": "AG4 - All 4-digit HS1992 commodities",
"parent": "#"
},
{
"id": "AG6",
"text": "AG6 - All 6-digit HS1992 commodities",
"parent": "#"
},
{
"id": "01",
"text": "01 - Animals; live",
"parent": "TOTAL"
},
{
"id": "0101",
"text": "0101 - Horses, asses, mules and hinnies; live",
"parent": "01"
},
{
"id": "010111",
"text": "010111 - Horses; live, pure-bred breeding animals",
"parent": "0101"
},
{
"id": "010119",
"text": "010119 - Horses; live, other than pure-bred breeding animals",
"parent": "0101"
},
{
"id": "010120",
"text": "010120 - Asses, mules and hinnies; live",
"parent": "0101"
},
{
"id": "0102",
"text": "0102 - Bovine animals; live",
"parent": "01"
},
{
"id": "010210",
"text": "010210 - Bovine animals; live, pure-bred breeding animals",
"parent": "0102"
},
{
"id": "010290",
"text": "010290 - Bovine animals; live, other than pure-bred breeding animals",
"parent": "0102"
},
{
"id": "0103",
"text": "0103 - Swine; live",
"parent": "01"
},
and so on.
What I would like to do is write a third file in which each row contains the explanation of the code (i.e. the expression that follows the word "text") in the corresponding line in the first file.
For example, the first three lines should be:
0101 - Horses, asses, mules and hinnies; live
0102 - Bovine animals; live
0103 - Swine; live
The only think I could come up with is an if cycle, but the code are 1233, so I'd have to write 1233 conditions.
Is there a shorter way? Maybe based on the fact that the codes are unique and the description is just after the code in the second file
Upvotes: 0
Views: 50
Reputation: 4152
As suggested by @mousetail the best way would be to import the second file as a dictionary with key being the code and text being the value.
import json
with open("path_to_file", "r") as json_file:
file_contents = json.load(json_file)
codes_to_text_dict = {result["id"]: result["text"] for result in file_contents["results"]}
Then just read the input file, find the text for each line and write it to the output file:
with open("input.txt") as input_file, open("output.txt", "w+") as output_file:
for line in input_file.readlines():
output_file.write(codes_to_text_dict[line.strip()] + "\n")
Upvotes: 2