Python把每个单词与注释成为一个字典,程序的功能就是管理一组单词记录,程序有查找单词(使用二分法查找单词)、增加单词、更新注释、删除单词、显示单词等功能.
时间: 2024-05-13 11:18:04 浏览: 129
xc.rar_单词查找_标准C
好的,那我们可以开始编写代码了。首先我们需要定义一个空的字典来存储单词和注释:
```python
word_dict = {}
```
接下来我们可以定义函数来实现各种功能。首先是增加单词的函数,我们可以让用户输入单词和注释,然后将它们添加到字典中:
```python
def add_word():
word = input("请输入单词:")
comment = input("请输入注释:")
word_dict[word] = comment
print("添加成功!")
```
接下来是删除单词的函数,我们可以让用户输入要删除的单词,然后从字典中删除它:
```python
def delete_word():
word = input("请输入要删除的单词:")
if word in word_dict:
del word_dict[word]
print("删除成功!")
else:
print("该单词不存在!")
```
然后是更新注释的函数,我们可以让用户输入要更新的单词和新的注释,然后将它们更新到字典中:
```python
def update_comment():
word = input("请输入要更新的单词:")
if word in word_dict:
comment = input("请输入新的注释:")
word_dict[word] = comment
print("更新成功!")
else:
print("该单词不存在!")
```
现在我们需要实现查找单词的函数,我们可以使用二分法来查找单词。首先我们需要将字典中的单词按照字母顺序排序,然后使用二分法查找单词:
```python
def search_word():
words = sorted(word_dict.keys())
left = 0
right = len(words) - 1
while left <= right:
mid = (left + right) // 2
if words[mid] == word:
print(words[mid] + ": " + word_dict[words[mid]])
return
elif words[mid] < word:
left = mid + 1
else:
right = mid - 1
print("该单词不存在!")
```
最后是显示单词的函数,我们可以将字典中的单词按照字母顺序打印出来:
```python
def display_words():
words = sorted(word_dict.keys())
for word in words:
print(word + ": " + word_dict[word])
```
现在我们可以将这些函数整合到一个程序中:
```python
word_dict = {}
def add_word():
word = input("请输入单词:")
comment = input("请输入注释:")
word_dict[word] = comment
print("添加成功!")
def delete_word():
word = input("请输入要删除的单词:")
if word in word_dict:
del word_dict[word]
print("删除成功!")
else:
print("该单词不存在!")
def update_comment():
word = input("请输入要更新的单词:")
if word in word_dict:
comment = input("请输入新的注释:")
word_dict[word] = comment
print("更新成功!")
else:
print("该单词不存在!")
def search_word():
word = input("请输入要查找的单词:")
words = sorted(word_dict.keys())
left = 0
right = len(words) - 1
while left <= right:
mid = (left + right) // 2
if words[mid] == word:
print(words[mid] + ": " + word_dict[words[mid]])
return
elif words[mid] < word:
left = mid + 1
else:
right = mid - 1
print("该单词不存在!")
def display_words():
words = sorted(word_dict.keys())
for word in words:
print(word + ": " + word_dict[word])
while True:
print("请选择操作:")
print("1. 添加单词")
print("2. 删除单词")
print("3. 更新注释")
print("4. 查找单词")
print("5. 显示单词")
print("0. 退出程序")
choice = input()
if choice == "1":
add_word()
elif choice == "2":
delete_word()
elif choice == "3":
update_comment()
elif choice == "4":
search_word()
elif choice == "5":
display_words()
elif choice == "0":
break
else:
print("无效的选择!")
```
阅读全文