Python - 将文本文件读入字典

时间:2015-12-07 10:50:43

标签: python loops dictionary

我有一个巨大的术语列表,我想从文本文件中提取并将它们分组到以下组之一:动物,艺术,建筑物,车辆,人,人,食物,玻璃,瓶子,标牌,口号,DJ,派对。我目前在tester2文件中有四个单词:

板 比萨 fearns 混合器

这是我的代码:

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']
 }

y = 0
while (y < 1):
    try:
        def search(keywords, searchFor):
            for item in keywords:
                for terms in keywords[item]:
                    if searchFor in terms:
                        print item



        with open("C:/Users/USERNAME/Desktop/tester2.txt") as termsdesk:
                for line in termsdesk:
                    this = search (keyword_dictionary, line)
                    this2 = str(this)
                    #print this2
                    #print item
    except KeyError:
        break
    y = y+1

我的结果应该是这样的:

Food
Food
Art
DJ

但我得到了这个:

DJ

我想象的是因为我的循环出了问题。有谁知道我需要改变什么?我试过移动&#34; while(y&lt; 1)&#34;但是我还没有能够得到我想要的结果。

2 个答案:

答案 0 :(得分:2)

从搜索字词中删除前导/尾随空格。以下按预期工作:

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

with open("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

此外,如果您希望搜索词的数量相对于词典的大小较大,可以考虑性能改进:您可以从任何单词构建反向映射到其类别。例如,变换:

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

进入

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

这种反向映射可以在开始时构建一次,然后在每个查询中重复使用,这样就可以将搜索功能转换为category_dict[term]。这样查找速度会更快,分摊O(1)复杂度,并且更容易编写。

答案 1 :(得分:2)

以下方法更有意义:

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}

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

这首先是你现有的词典并反过来,以便更容易查找每个单词。

这将为您提供以下输出:

Food
Food
Art
DJ