Skip to content Skip to sidebar Skip to footer

Python - Reading Text File Into Dictionary

I have a huge list of terms that I want to pull from a text file and get them grouped into one of the following groups: Animal, Art, Buildings, Vehicle, Person, People, Food, Glass

Solution 1:

Remove leading / trailing whitespace from the search term. The following works as expected:

defsearch(keywords, searchFor):
    for key, words in keywords.iteritems():
        if searchFor in words:
           print key

withopen("tester2.txt") as termsdesk:
    for line in termsdesk:
        this = search(keyword_dictionary, line.strip())
        this2 = str(this)



$ cat tester2.txt 
plate
pizza
fearns
mixer

$ python test4.py 
Food
Food
Art
DJ

Also, here is a performance improvement you could consider if you expect the number of search terms to be large relative to the size of the dictionary: you could build a reverse mapping from any word to its category. For example transform:

keyword_dict = {'DJ': ['mixer', 'speakers']}

into

category_dict = {
 'mixer': 'DJ',
 'speakers':'DJ'
}

This reverse mapping could be built once at the start and then reused for every query, this way turning your search function into just category_dict[term]. This way the look-up will be faster, amortised O(1) complexity, and easier to write.

Solution 2:

The following approach would make more sense:

keyword_dictionary = {
    'Animal' : ['animal', 'dog', 'cat'],
    'Art' : ['art', 'sculpture', 'fearns'],
    'Buildings' : ['building', 'architecture', 'gothic', 'skyscraper'],
    'Vehicle' : ['car','formula','f-1','f1','f 1','f one','f-one','moped','mo ped','mo-ped','scooter'],
    'Person' : ['person','dress','shirt','woman','man','attractive','adult','smiling','sleeveless','halter','spectacles','button','bodycon'],
    'People' : ['people','women','men','attractive','adults','smiling','group','two','three','four','five','six','seven','eight','nine','ten','2','3','4','5','6','7','8','9','10'],
    'Food' : ['food','plate','chicken','steak','pizza','pasta','meal','asian','beef','cake','candy','food pyramid','spaghetti','curry','lamb','sushi','meatballs','biscuit','apples','meat','mushroom','jelly', 'sorbet','nacho','burrito','taco','cheese'],
    'Glass' : ['glass','drink','container','glasses','cup'],
    'Bottle' : ['bottle','drink'],
    'Signage' : ['sign','martini','ad','advert','card','bottles','logo','mat','chalkboard','blackboard'],
    'Slogan' : ['Luck is overrated'],
    'DJ' : ['dj','disc','jockey','mixer','instrument','turntable'],
    'Party' : ['party']
}

terms = {v2 : k for k, v in keyword_dictionary.items() for v2 in v}

withopen('input.txt', 'r') as f_input:
    for word in f_input:
        print terms[word.strip()]

This first takes your existing dictionary and make a reverse of it to make it easier to lookup each word.

This will give you the following output:

Food
Food
Art
DJ

Post a Comment for "Python - Reading Text File Into Dictionary"