制作英文学习词典。编写程序制作英文学习词典,词典有3个基本功能:添加、查询和退出。程序读取源文件径下的txt格式词典文件,若没有就创建一个。词典文件存储方式为“英文单词 中文单词”,每行仅有一对中英释义。程序会根据用户的选择进入相应的功能模块,并显示相应的操作提示。当添加的单词已存在时,显示“该单词已添加到字典库”;当查询的单词不存在时,显示“字典库中未找到这个单词”。用户输入其他选项时,提示“输入有误”。给出完整的代码
时间: 2024-03-27 21:36:51 浏览: 162
好的,以下是完整的英文学习词典代码:
```python
import os
filename = "dictionary.txt"
# Check if file exists, otherwise create it
if not os.path.isfile(filename):
open(filename, 'w').close()
def add_word():
word = input("Enter the English word: ")
meaning = input("Enter the Chinese meaning: ")
# Check if word already exists
with open(filename, 'r') as f:
for line in f:
if word in line:
print("This word already exists in the dictionary.")
return
# Add word to dictionary
with open(filename, 'a') as f:
f.write(word + " " + meaning + "\n")
print("Word added to dictionary.")
def search_word():
word = input("Enter the English word: ")
# Search for word in dictionary
with open(filename, 'r') as f:
for line in f:
if word in line:
print(line.strip())
return
# Word not found
print("This word does not exist in the dictionary.")
def quit_program():
print("Goodbye!")
quit()
while True:
print("Select an option:")
print("1. Add a word")
print("2. Search for a word")
print("3. Quit")
choice = input("Enter an option number: ")
if choice == "1":
add_word()
elif choice == "2":
search_word()
elif choice == "3":
quit_program()
else:
print("Invalid input. Please enter a valid option number.")
```
在这个代码中,我们首先使用了os模块来检查词典文件是否存在,如果不存在就创建一个txt文件。然后我们定义了三个函数来执行添加、查询和退出功能。在add_word()函数中,我们首先读取用户输入的单词和释义,然后检查它是否已经存在于词典中。如果单词已经存在,我们向用户显示相应的消息。否则,我们将单词和释义添加到词典文件中。在search_word()函数中,我们首先读取用户输入的单词,然后在词典文件中查找它。如果单词不存在,我们向用户显示相应的消息。最后,在quit_program()函数中,我们向用户显示退出消息并退出程序。在主循环中,我们为用户提供菜单来选择所需的操作,并根据选择执行相应的函数。如果用户输入了无效的选项,我们向用户显示相应的消息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)