编写一个小词典程序可以通过多种编程语言实现,下面我将提供一个简单的Python示例,以及一个C语言示例。
Python示例
```python
import os
词典文件路径
DICTIONARY_FILE = 'dictionary.txt'
初始化词典
def initialize_dictionary():
if not os.path.exists(DICTIONARY_FILE):
with open(DICTIONARY_FILE, 'w', encoding='utf-8') as file:
file.write('Hello\nWorld\n')
添加单词
def add_word(word, definition):
with open(DICTIONARY_FILE, 'a', encoding='utf-8') as file:
file.write(f'{word}\n{definition}\n')
查询单词
def search_word(word):
with open(DICTIONARY_FILE, 'r', encoding='utf-8') as file:
for line in file:
if line.startswith(word):
return line[len(word)+1:].strip()
return 'Word not found'
显示菜单
def print_menu():
print('1. Add word')
print('2. Search word')
print('3. Exit')
主程序
def main():
initialize_dictionary()
while True:
print_menu()
choice = input('Enter your choice: ')
if choice == '1':
word = input('Enter word: ')
definition = input('Enter definition: ')
add_word(word, definition)
print('Word added successfully.')
elif choice == '2':
word = input('Enter word to search: ')
print(search_word(word))
elif choice == '3':
print('Exiting...')
break
else:
print('Invalid choice. Please try again.')
if __name__ == '__main__':
main()
```
C语言示例