<python>将动态词库保存于txt文件中

这篇博客介绍了一个使用Python编写的程序,该程序允许用户输入同义词对并将其保存到txt文件中。程序包含添加、删除和玩猜词游戏的功能,所有操作都能实时更新txt文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用来进行猜同义词的小游戏:使用者先输入至少一对同义词,python会生成一个txt文件将其保存;之后可以进行猜词游戏,或者新增/删除/补充同义词,所有修改都会被实时保存到txt中;

 main function:

import add
import remove
import play

# ask user to play the game or add synonym
def guess_or_add():
    try:
        print('The game has begun! Please select your choice:  ')
        print('a)  Add synonyms')
        print('b)  Play the game ')
        choice = input('Your choice:   ')
        if choice == 'a':
            add.add_synonym()
        elif choice == 'b':
            play.play_the_game()
        else:
            print('Sorry your input is invalid')
            print()
            guess_or_add()
    except ValueError:
        print('Sorry something is wrong with your input.')
        print('Quitting...')



def make_selection():
    try:
        print()
        print()
        print('Please select your choice:')
        print('a)  Play the game.')
        print('b)  Edit the dictionary.')
        print('c)  Quit.')
        choice = input('Your choice:     ')
        if choice == 'a':
            play.play_the_game()
        elif choice == 'b':
            dic = read_dic_from_text()
            key_list = []
            for key in dic:
                key_list.append(key)

            if len(key_list) < 1:
                print('Sorry, your dictionary is empty.Please add some synonyms first before editing.')
                word = input('Please enter a new word:    ')
                add.add_new_word(word)
            else:
                print()
                print('The following words are in your dictionary: ')
                for item in key_list:
                    print('  *' + item)
                print()
                print('Please select your choice:')
                print('a)  Adding')
                print('b)  Removing.')
                print('c)  Quit.')
                choice = input('Your choice:     ')
                if choice == 'a':
                    add.add_synonym()
                elif choice == 'b':
                    remove.check_before_remove()
                elif choice == 'c':
                            print('Quitting...')
                else:
                    print('Sorry your input is invalid')
                    make_selection()
        elif choice == 'c':
            print('Quitting...')
        else:
            print('Sorry your input is invalid')
            make_selection()
    except ValueError:
        print('Sorry something is wrong with your input.')
        print('Quitting...')


#read the existing text and create a dictionary
def read_dic_from_text():
    dic = {}
    try:
        f = open('synonyms_dic.txt', 'r')
        for line in f:
            word_number = len(line.split())
            if word_number < 2:
                print('Sorry the dictionary is empty.Please add a new word first.')
                word = input('Please enter a new word:     ')
                add.add_new_word(word)
            elif word_number == 2:
                (key,val) = line.split()
                dic[key] = val
            elif word_number == 3:
                (key,val1,val2) = line.split()
                dic[key] = val1,val2
            elif word_number == 4:
                (key, val1, val2,val3) = line.split()
                dic[key] = val1, val2,val3
            elif word_number == 5:
                (key, val1, val2,val3,val4) = line.split()
                dic[key] = val1, val2,val3,val4
            elif word_number == 6:
                (key, val1, val2,val3,val4,val5) = line.split()
                dic[key] = val1, val2,val3,val4,val5
            elif word_number == 7:
                (key, val1, val2,val3,val4,val5,val6) = line.split()
                dic[key] = val1, val2,val3,val4,val5,val6
        f.close()
        return dic
    except FileNotFoundError:
        print('No file found now.')
        print('Add a new word, and a file will be created.')




#_____________________________  main  function  ____________________________________________________
def main():
    guess_or_add()


if __name__ =='__main__':
    main()

 

 

module add:

import main


#_______________________________________________  add  _________________________________
# check the input word : whether existing or new
def add_synonym():
    dic = main.read_dic_from_text()
    word = input('Please enter the word you would like to add:   ')
    if len(word) <= 1:
        print('Sorry you cannot enter a single letter.')
        print()
        add_synonym()
    else:
        for key in dic:
            if key == word:
                add_to_existing_word(word)
                return True
        add_new_word(word)

# when the input word already exist in the dictionary
def add_to_existing_word(word):
    f = open("synonyms_dic.txt", "r")
    h = open("tempo1.txt", "w")
    lines = f.readlines()
    for line in lines:
        if not line.startswith(word + ' '):
            h.write(line)
    f.close()
    h.close()

    dic = main.read_dic_from_text()

    f = open("synonyms_dic.txt", "w")
    h = open("tempo1.txt", "r")
    lines = h.readlines()
    for line in lines:
        if not line.startswith(word + ' '):
            f.write(line)
    f.close()
    h.close()

    print()
    print('The word ' + word + ' has the following synonyms: ')
    original_item_list = []

    for item in dic[word]:
        if len(item) == 1:
            print('  *' + ''.join(dic[word]))
        else:
            original_item_list.append(item)
            print('  *' + item)

    if len(original_item_list) == 6:
        print('Sorry you can have at most 6 synonyms for one word.')
        print('You cannot add more synonyms to this word.')
        main.make_selection()
    else:
        new_line = ''
        for i in range(0, len(original_item_list)):
            new_line = new_line + str(original_item_list[i] + ' ')
        # check the length of the input synonym: it cannot be a single letter
        new_synonym = input('Please enter another synonym for this word:   ')
        if len(new_synonym) < 2:
            print('Sorry you cannot enter a single letter.')
            main.make_selection()
        else:
            f = open("synonyms_dic.txt", "a")
            f.write(word + ' ' + str(new_line) + new_synonym + '\n')
            f.close()
            print('The synonym has been added to the dictionary.')
            main.make_selection()


# when the input word is new to the dictionary
def add_new_word(word):
    first_synonym = input('Please enter the first synonym for this word:    ')
    second_synonym = input('Please enter the second synonym for this word:    ')

    f = open('synonyms_dic.txt', 'a')
    f.write(word+' '+first_synonym+' '+second_synonym+'\n')
    f.close()
    print()
    print('The synonyms have been added to the dictionary.')
    main.make_selection()




module remove:

import add
import main


#_________________________________________  remove  _________________________________________
# if there is only one synonym for a word, the synonym will be splited
#for example : the word 'father' has only one synonym 'dad' ; python will automatically split it into d-a-d and return 3 synonyms
#this function checks whether the only one synonym is splited. If so , concatenate them with join().
def check_before_remove():
    word = input('Please enter the word that you want to remove:   ')
    dic = main.read_dic_from_text()
    key_list = []
    for key in dic :
        key_list.append(key)
    #check whether the dictionary is empty
    if len(key_list) == 0:
        print('Sorry you cannot delete from an empty dictionary.')
        word = input('Please enter a new word:   ')
        add.add_new_word(word)

    #check if the user input word is in the dictionary
    if word in key_list:
        #check if this word only has one synonym
        if len(dic[word][0]) == 1:
            print('The word ' + word + ' only has the only one synonym: ')
            print('  *' + ''.join(dic[word]))
            print()
            remove_entire_word_and_synonym_list(word)
        else:
            remove_items(word)

    else:
        print()
        print('Your input is invalid.Please type the word again.')
        check_before_remove()



# show the synonyms of this word and ask the user whether to delete a single synonym or entire lists
def remove_items(word):
    dic = main.read_dic_from_text()
    print()
    print('The word ' + '"' + word + '"' + ' has the following synonyms: ')
    original_item_list = list(dic[word])
    for item in dic[word]:
        original_item_list.append(item)
        print('  *' + item)

    print()
    print('Please select your choice:  ')
    print('a)  Remove single synonyms from this word.')
    print('b)  Remove this word and entire list.')
    choice = input('Your choice:   ')
    if choice == 'a':
        remove_single_synonym(word)
    elif choice == 'b':
        remove_entire_word_and_synonym_list(word)
    else:
        print('Sorry your input is invalid')
        remove_items(word)

#remove single synonym from a specific word
def remove_single_synonym(word):

    f = open("synonyms_dic.txt", "r")
    h = open("tempo.txt", "w")
    lines = f.readlines()
    for line in lines:
        if not line.startswith(word + ' '):
            h.write(line)
    f.close()
    h.close()

    dic = main.read_dic_from_text()

    f = open("synonyms_dic.txt", "w")
    h = open("tempo.txt", "r")
    lines = h.readlines()
    for line in lines:
        if not line.startswith(word + ' '):
            f.write(line)
    f.close()
    h.close()

    delete_synonym = input('Please enter the single synonym you want to delete:   ')
    original_item_list = []
    for item in dic[word]:
        original_item_list.append(item)
    if delete_synonym in original_item_list:
        original_item_list.remove(delete_synonym)
        f = open("synonyms_dic.txt", "a")
        new_line = ''
        for item in original_item_list:
            new_line = new_line + item + ' '
        f.write(word + ' ' + new_line)
        f.close()
        print('The single synonym has been deleted from this word.')
        main.make_selection()
    else:
        print('Sorry your input is invalid. Please type again.')
        remove_single_synonym(word)


#remove entire word and synonym list
def remove_entire_word_and_synonym_list(word):

    f = open("synonyms_dic.txt", "r")
    h = open("tempo2.txt", "w")
    lines = f.readlines()
    for line in lines:
        if not line.startswith(word + ' '):
            h.write(line)
    f.close()
    h.close()

    f = open("synonyms_dic.txt", "w")
    h = open("tempo2.txt", "r")
    lines = h.readlines()
    for line in lines:
        f.write(line)
    f.close()
    h.close()

    print('The word and synonym list have been successfully deleted.')
    main.make_selection()

module play:

import add
import main


#_________________________________________  remove  _________________________________________
# if there is only one synonym for a word, the synonym will be splited
#for example : the word 'father' has only one synonym 'dad' ; python will automatically split it into d-a-d and return 3 synonyms
#this function checks whether the only one synonym is splited. If so , concatenate them with join().
def check_before_remove():
    word = input('Please enter the word that you want to remove:   ')
    dic = main.read_dic_from_text()
    key_list = []
    for key in dic :
        key_list.append(key)
    #check whether the dictionary is empty
    if len(key_list) == 0:
        print('Sorry you cannot delete from an empty dictionary.')
        word = input('Please enter a new word:   ')
        add.add_new_word(word)

    #check if the user input word is in the dictionary
    if word in key_list:
        #check if this word only has one synonym
        if len(dic[word][0]) == 1:
            print('The word ' + word + ' only has the only one synonym: ')
            print('  *' + ''.join(dic[word]))
            print()
            remove_entire_word_and_synonym_list(word)
        else:
            remove_items(word)

    else:
        print()
        print('Your input is invalid.Please type the word again.')
        check_before_remove()



# show the synonyms of this word and ask the user whether to delete a single synonym or entire lists
def remove_items(word):
    dic = main.read_dic_from_text()
    print()
    print('The word ' + '"' + word + '"' + ' has the following synonyms: ')
    original_item_list = list(dic[word])
    for item in dic[word]:
        original_item_list.append(item)
        print('  *' + item)

    print()
    print('Please select your choice:  ')
    print('a)  Remove single synonyms from this word.')
    print('b)  Remove this word and entire list.')
    choice = input('Your choice:   ')
    if choice == 'a':
        remove_single_synonym(word)
    elif choice == 'b':
        remove_entire_word_and_synonym_list(word)
    else:
        print('Sorry your input is invalid')
        remove_items(word)

#remove single synonym from a specific word
def remove_single_synonym(word):

    f = open("synonyms_dic.txt", "r")
    h = open("tempo.txt", "w")
    lines = f.readlines()
    for line in lines:
        if not line.startswith(word + ' '):
            h.write(line)
    f.close()
    h.close()

    dic = main.read_dic_from_text()

    f = open("synonyms_dic.txt", "w")
    h = open("tempo.txt", "r")
    lines = h.readlines()
    for line in lines:
        if not line.startswith(word + ' '):
            f.write(line)
    f.close()
    h.close()

    delete_synonym = input('Please enter the single synonym you want to delete:   ')
    original_item_list = []
    for item in dic[word]:
        original_item_list.append(item)
    if delete_synonym in original_item_list:
        original_item_list.remove(delete_synonym)
        f = open("synonyms_dic.txt", "a")
        new_line = ''
        for item in original_item_list:
            new_line = new_line + item + ' '
        f.write(word + ' ' + new_line)
        f.close()
        print('The single synonym has been deleted from this word.')
        main.make_selection()
    else:
        print('Sorry your input is invalid. Please type again.')
        remove_single_synonym(word)


#remove entire word and synonym list
def remove_entire_word_and_synonym_list(word):

    f = open("synonyms_dic.txt", "r")
    h = open("tempo2.txt", "w")
    lines = f.readlines()
    for line in lines:
        if not line.startswith(word + ' '):
            h.write(line)
    f.close()
    h.close()

    f = open("synonyms_dic.txt", "w")
    h = open("tempo2.txt", "r")
    lines = h.readlines()
    for line in lines:
        f.write(line)
    f.close()
    h.close()

    print('The word and synonym list have been successfully deleted.')
    main.make_selection()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值