在我的代码中,我在字典中有键(概念)。运行时,与(概念)中的键匹配的输入将打印字典(文件)中的匹配值。现在,我尝试在当前输出的底部打印,字典(文件)中的值与输入中输入的确切值匹配。在这种情况下,如果您输入“机器学习游戏”,您将获得-
输入概念想法:机器学习游戏 file0004.txt file0009.txt file0009.txt file0009.txt file0004.txt file0008.txt file0004.txt file0009.txt file0004.txt file0009.txt file0004.txt file0008.txt http://file0001.txt file0002.txt file0004.txt file0003.txt file0003.txt file0008.txt
但是,files0008.txt是唯一与在dictionary(concept)值中存在的确切特定键-((number“ 8”)))匹配的唯一值。我想要一个值或任何精确值(可能有多个匹配的精确值)并将其列出在其他单个输出下面。像-
唯一值输出:file0008.txt
========================代码===================== =====
def concept(phrase):
# split var(phrase) at spaces and assign to var(words)
words = phrase.split()
# use this to list python file titles and links to open them
files = {1:"http://file0001.txt",
2:"file0002.txt",
3:"file0003.txt",
4:"file0004.txt",
5:"file0005.txt",
6:"file0006.txt",
7:"file0007.txt",
8:"file0008.txt",
9:"file0009.txt"}
# change keys to searchable simple keyword phrases.
concepts = {'GAMES':[1,2,4,3,3,8],
'BLACKJACK':[5,3,5,3,5],
'MACHINE':[4,9,9,9,4,8],
'DATABASE':[5,3,3,3,5],
'LEARNING':[4,9,4,9,4,8]}
# iterate through all var(words) found in var(word)
for word in words:
# convert to uppercase, search var(word) in dict 'concepts', if not found return not found"
if word.upper() not in concepts:
print("\n'{}':Not Found in Database \n" .format(word)) not in concepts
else:
# for matching keys in dict 'concept' list values in dict 'files'
for pattern in concepts[word.upper()]:
print(files[pattern])
# return input box at end of query
while True:
concept(input("Enter Concept Idea: "))
答案 0 :(得分:0)
如果我理解您的想法,那么如果短语中的所有单词都与该文件相关联,那么您想要的是concept()函数仅打印文件名,并且您希望它打印所有文件名
如果是这样,则使用集合代替列表很有意义。通过采用两个集合的交集,您最终得到的集合中只有两个集合中的元素。
除了一些间距问题之外,您的思维中似乎还存在两个错误:不仅文件8匹配,文件4也匹配;并且您写了“机器学习游戏”,但您可能指的是“机器学习游戏”。
遵循脚本的模式,但是使用集合而不是列表:
def concept(phrase):
words = phrase.upper().split()
files = {
1:"http://file0001.txt",
2:"file0002.txt",
3:"file0003.txt",
4:"file0004.txt",
5:"file0005.txt",
6:"file0006.txt",
7:"file0007.txt",
8:"file0008.txt",
9:"file0009.txt"
}
concepts = {
'GAMES': {1, 2, 4, 3, 3, 8},
'BLACKJACK': {5, 3, 5, 3, 5},
'MACHINE': {4, 9, 9, 9, 4, 8},
'DATABASE': {5, 3, 3, 3, 5},
'LEARNING': {4, 9, 4, 9, 4, 8}
}
# start with all files
matching_files = set(files.keys())
for word in words:
if word in concepts:
matching_files = matching_files & concepts[word]
# print the resulting files
for match in matching_files:
print(files[match])
while True:
concept(input("Enter Concept Idea: "))