简体   繁体   English

Python-将文本文件读入字典

[英]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, Bottle, Signage, Slogan, DJ, Party. 我有很多要从文本文件中提取的术语列表,并将它们分为以下组之一:动物,艺术,建筑物,车辆,人,人,食品,玻璃,瓶,标牌,标语,DJ , 派对。 I currently have four words in the tester2 file: 我目前在tester2文件中有四个词:

plate pizza fearns mixer 盘比萨担心搅拌机

Here's my code: 这是我的代码:

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

My results should look something like this: 我的结果应如下所示:

Food
Food
Art
DJ

But instead I get this: 但是我得到了这个:

DJ

I imagine it's because there's something wrong with my loop. 我想这是因为我的循环有问题。 Does anyone know what I need to change? 有人知道我需要更改吗? I've tried moving the "while (y<1)" around but I haven't been able to get the results I want. 我已经尝试过移动“ while(y <1)”,但是却无法获得想要的结果。

Remove leading / trailing whitespace from the search term. 从搜索词中删除前导/尾随空格。 The following works as expected: 预期的工作如下:

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

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] . 可以在开始时构建一次反向映射,然后将其用于每个查询,这样您的搜索功能就变成了category_dict[term] This way the look-up will be faster, amortised O(1) complexity, and easier to write. 这样,查找将更快,摊销O(1)复杂度并且更容易编写。

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}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM