I've got a txt file of all the countries in the world and what kind of products do they export.
This is what one line looks like without any splitting or stripping (notice \t
and \n
):
[Jamaica\t alumina, bauxite, sugar, rum, coffee, yams, beverages, chemicals, wearing apparel, mineral fuels\n]
I have to write a program which does that:
Angola
[ 'oil,', 'diamonds,', 'refined', 'petroleum', 'products,', 'coffee,', 'sisal,', 'fish,', 'fish', 'products,', 'timber,', 'cotton']
Anguilla
[ 'lobster,', 'fish,', 'livestock,', 'salt,', 'concrete', 'blocks,', 'rum']
Antigua and Barbuda
[ 'petroleum', 'products,', 'bedding,', 'handicrafts,', 'electronic', 'components,', 'transport', 'equipment,', 'food,', 'live', 'animals']
Argentina
[ 'soybeans,', 'petroleum,', 'gas,', 'vehicles,', 'corn,', 'wheat']
This is what I've done so far but from now on I don't know how to go forward:
import os
file=open("exports.txt",'r')
list=[]
for i in file:
list.append(i.split(" "))
for i in range(len(list)):
print(list[i])
As a result I get a list of every country and what does it export:
['Angola\t', 'oil,', 'diamonds,', 'refined', 'petroleum', 'products,', 'coffee,', 'sisal,', 'fish,', 'fish', 'products,', 'timber,', 'cotton\n']
['Anguilla\t', 'lobster,', 'fish,', 'livestock,', 'salt,', 'concrete', 'blocks,', 'rum\n']
['Antigua', 'and', 'Barbuda\t', 'petroleum', 'products,', 'bedding,', 'handicrafts,', 'electronic', 'components,', 'transport', 'equipment,', 'food,', 'live', 'animals\n']
['Argentina\t', 'soybeans,', 'petroleum,', 'gas,', 'vehicles,', 'corn,', 'wheat\n']
How do I countinue? Thanks for help
This should do it
with open("exports.txt",'r') as infile:
exports = {}
for line in infile:
parts = line.partition('\t')
exports[parts[0]] = parts[-1].strip().split(', ')
for country, exports in exports.iteritems():
print country
print exports
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With