我使用的是一个单词本的txt文件,文件名为word.txt
f = "word.txt" # 用变量f接收word.txt的路径 此时我的文件和我的程序在同一级目录,如果你的不在同级目录,需要填写完整路径
a = open(f, encoding='utf-8') # 变量a接收文件,指定字符级为utf-8
b = list(a) # 把接收的数据转换为列表,放入变量b中
a.close() # 关闭文件
return b # 返回变量b 此时b中为列表化的文件数据
def find_word(x, y: list): # 定义函数,接收两个形参(x为需要查询的数据,y为查询的数据库)第二个形参y类型为list
cou = 0 # 增加一个序号
for i in y: # 循环接收到的列表
if x in i: # 判断如果x(查询的数据)在列表中
cou += 1
print(str(cou) + ".", i.replace(x, f"\033[31m{x}\033[0m"), end="") # 输出字符串类型序号,使用replace替换,达到高亮效果
def main_():
lis = open_file() # lis = open_file()这个函数的返回值时变量b,所有lis有了列表类型文件所有数据
while True: # 写一个循环
lis = open_file()
print("词库加载成功.....")
word = input("需要查询的值,输入Q退出: ") # word 接收一个输入的需要查询的值
if word == "Q" and word == "q": # 如果输入q或Q为退出
break
find_word(word,lis) # 调用查找函数,传入word和lis
if __name__ == '__main__':
main_()
方法二:
# 作业1.电子词典(模糊查询,高亮显示)
def get_word_list() -> list:
f = open("word.txt", encoding="utf-8")
results = f.readlines()
f.close()
return results
def find_word(w: str, lis: list) -> None:
count = 0
for row in lis:
if w in row:
count += 1
print(str(count) + ".", row.replace(w, f"\033[31m{w}\033[0m"), end="")
def main():
lis = get_word_list()
print("词库加载成功....")
while True:
word = input("请输入您要查询的单词或汉字,Q退出:")
if word == "Q":
break
find_word(word, lis)
if __name__ == '__main__':
main()