如何用Python3实现Dictionary?

这个程序使用python的容器,名为 词典 (在字典中,一个键与一些信息相关联)。这个程序将把一个单词作为输入,并返回该单词的意思。 Python3应该安装在您的系统中。如果未安装,请从此安装 链接 。始终尝试安装最新版本。

null

我制作了一个文本文件,其中单词及其含义以python的字典格式存储 例子:

data = {"geek" : "engage in or discuss computer-related tasks 
obsessively or with great attention to technical detail."}

在这里,如果我们从数据中称之为“极客”,那么这将返回其含义“痴迷地从事或讨论与计算机相关的任务,或者非常关注技术细节”。

这个python程序允许您获取这个文本文件的数据并给出其含义。

# Python3 Code for implementing
# dictionary
# importing json library
import json
# importing get_close_matches function from difflib library
from difflib import get_close_matches
# loading data
data = json.load( open ( "data.txt" ))
# defining function meaning
def meaning(w):
# converting all the letters of "w" to lower case
w = w.lower()
# checking if "w" is in data
if w in data:
return data[w]
# if word is not in data then get close match of the word
elif len (get_close_matches(w, data.keys())) > 0 :
# asking user for his feedback
# get_close_matches returns a list of the best
# “good enough” matches choosing first close
# match "get_close_matches(w, data.keys())[0]"
yn = input ("Did you mean % s instead? Enter Y if yes, or N if no:
" % get_close_matches(w, data.keys())[ 0 ])
if yn = = "Y" :
return data[get_close_matches(w, data.keys())[ 0 ]]
elif yn = = "N" :
return "The word doesn't exist in our data."
else :
return "We didn't understand your entry."
else :
return "The word doesn't exist in our data."
# asking word from user to get the meaning
word = input ( "Enter word: " )
# storing return value in "output"
output = meaning(word)
# if output type is list then print all element of the list
if type (output) = = list :
for item in output:
print (item)
# if output type is not "list" then print output only
else :
print (output)


如何跑步?

  1. 下载 并将其保存在保存python代码文件的同一文件夹中。
  2. 确保文件(数据文件和代码文件)位于同一文件夹中。 图片[1]-如何用Python3实现Dictionary?-yiteyi-C++库
  3. 打开该文件夹中的命令提示符,按shift键,然后右键单击鼠标。 图片[2]-如何用Python3实现Dictionary?-yiteyi-C++库
  4. 使用cmd(命令提示符)运行python代码。 图片[3]-如何用Python3实现Dictionary?-yiteyi-C++库
  5. 输入要搜索的单词。 图片[4]-如何用Python3实现Dictionary?-yiteyi-C++库
  6. 输出将是您的结果。 图片[5]-如何用Python3实现Dictionary?-yiteyi-C++库

    视频演示

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享