近来看文献,总是遇到这样的问题。
看文献总是需要查找一些生词以理解文章。但是目前似乎没有哪个软件可以管理自己不会的生词,干脆自己结合CHATGPT写了一个简单脚本,生成属于自己的生词表。
代码如下:
import os
def add_to_dictionary(word, translation, dictionary):
word_lower = word.lower()
dictionary[word_lower] = translation
def save_dictionary(dictionary, filename):
with open(filename, 'w') as f:
max_word_length = max(len(word) for word in dictionary.keys())
for word, translation in sorted(dictionary.items()):
if word.strip() == '&':
continue # 跳过单词为 & 的行
# 计算填充空格的数量
word_padding = max_word_length - len(word)
translation_padding = max_word_length - len(translation)
# 写入文件
f.write(f"{word}{' ' * word_padding} {translation}{' ' * translation_padding}\n")
def load_dictionary(filename):
try:
with open(filename, 'r') as f:
dictionary = {}
for line in f:
parts = line.strip().split(':')
if len(parts) >= 2: # 检查分割后的列表长度是否大于等于 2
key = parts[0].strip()
value = ':'.join(parts[1:]).strip()
dictionary[key] = value
return dictionary
except FileNotFoundError:
return {}
def create_empty_file(filename):
if not os.path.exists(filename):
open(filename, 'w').close() # 创建一个空文件
def main():
# 获取当前脚本所在目录
script_directory = os.path.dirname(os.path.abspath(__file__))
filename = os.path.join(script_directory, "dictionary.txt")
# 创建空文件(如果不存在)
create_empty_file(filename)
custom_dictionary = load_dictionary(filename)
while True:
user_input = input("请输入单词和翻译,用空格隔开(输入 q 退出):")
if user_input.lower() == 'q':
break
input_parts = user_input.split(maxsplit=1)
if len(input_parts) >= 2:
word, translation = input_parts
add_to_dictionary(word, translation, custom_dictionary)
save_dictionary(custom_dictionary, filename)
print(f"已添加到字典:{word} -> {translation}")
else:
print("输入格式错误,请重新输入!")
print("退出程序。")
if __name__ == "__main__":
main()
代码目前功能比较简单,不过已经可以满足我的需求了。以上代码主要由CHATGPT生成,自己仅做了部分修改。以后有更多功能再更新吧。