我有一个庞大的术语列表,我想从一个文本文件中提取出来,并将它们分为以下组之一:动物、艺术、建筑、车辆、人、人、食物、玻璃、瓶子、标牌、标语、DJ、派对。我目前在tester2文件中有四个词:
板 披萨 费恩斯 搅拌机
我的代码是:
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
我的结果应该是这样的:
^{pr2}$但我得到的却是:
DJ
我想是因为我的循环出了问题。有人知道我需要改变什么吗?我试过移动“while(y<;1)”按钮,但没能得到我想要的结果。在
以下方法更有意义:
这首先使用现有的词典,并将其反过来,以便更容易地查找每个单词。在
这将为您提供以下输出:
^{pr2}$从搜索词中删除前导/尾随空格。以下工作如预期:
如果你能从字典里找到一个更大的词类,你也可以考虑到它的搜索性能。例如变换:
^{pr2}$进入
这种反向映射可以在开始时构建一次,然后在每个查询中重用,这样就可以将搜索函数转换为
category_dict[term]
。这样的话,查找将更快、更复杂、更易于编写。在相关问题 更多 >
编程相关推荐