字典消失

  • 本文关键字:消失 字典 python
  • 更新时间 :
  • 英文 :


我正在尝试为单词列表分配分数(例如,惊讶= 7,真棒= 10(,但是,似乎每次调用函数后我的字典都会完全重置。我该怎么做才能确保我的字典保持不变,以便我可以使用它为列表中的下一个列表分配分数?这是我的代码:

data = open("keywords.txt","r")
def main():
    list = [["haha", "amazed", "amazing"], ["great", "wow", "awesome"]]
    print(keyword_check(list[0]))
    print(keyword_check(list[1]))
def keyword_check(list):
    keywords = []
    words = []
    numbers = []
    score_list = []
    total_score = 0
    dictionary = {}
    for i in data.readlines():
        list_split = i.split(",")
        list_stripped = [x.strip() for x in list_split]#for entries in i]
        keywords.append(list_stripped)
    file_length = len(keywords)
    for i in range(file_length):
        word = keywords[i][0]
        number = keywords[i][1]
        words.append(word)
        numbers.append(number)
    for i in range(file_length):
        dictionary[words[i]] = numbers[i]
    for i in list:
        if i in dictionary:
            score = dictionary[i]
            score_list.append(score)
    for i in score_list:
        total_score += int(i)
    return(dictionary, score_list, total_score)
main()

data.close()

你在 keyword_check 中显式重置了你的字典,所以它当然不能按预期工作。解决此问题的一种方法是在main中定义字典并将其作为参数传递给另一个函数:

def main():
    list = [["haha", "amazed", "amazing"], ["great", "wow", "awesome"]]
    dictionary = {}
    print(keyword_check(list[0], dictionary))
    print(keyword_check(list[1], dictionary))
def keyword_check(list, dictionary):
    keywords = []
    words = []
    numbers = []
    score_list = []
    total_score = 0
    # dictionary = {} remove that line
    ...

最新更新