Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print something and then its list?

Tags:

python

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

like image 456
user1824179 Avatar asked Nov 14 '12 15:11

user1824179


1 Answers

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

like image 61
inspectorG4dget Avatar answered Nov 05 '22 18:11

inspectorG4dget