首页 > 技术文章 > 字典中找不到对应的键的处理方法

zero17 2022-04-05 20:37 原文

def Count_word(file_name):
    # 编译正则表达式模式,查找所有字母(>=1)
    word_re = re.compile(r'\w+')
    # 定义索引字典
    index = {}
    # index = collections.defaultdict(list)
    with open(file_name, encoding='utf-8') as fp:
        # 遍历文件 从第一行开始  enimerate(sequence, startindex)
        # 行号  行内容
        for line_no, line in enumerate(fp, 1):
            # 每行内容查找,返回迭代器
            for match in word_re.finditer(line):
                # 返回匹配到的字符串
                word = match.group()
                # 行中匹配到的index(默认为0) + 1
                column_no = match.start()
                # 行号 行中出现的索引开始位置
                location = (line_no, column_no)

                # 列表中查找不到键的第一种处理方式
                # 查找index字典中是否存在word,不存在把 word [] 放入index{}
                occurrences = index.get(word, [])
                occurrences.append(location)
                index[word] = occurrences

                # 列表中查找不到键的第二种处理方式
                # setdefault
                index.setdefault(word, []).append(location)
                #
                # 第三种处理方式  defaultdict
                # 将list构造方法作为字典中默认的元素形式
                index = collections.defaultdict(list)
                # 如果字典中找不到word,上面一句就会被调用,为查询不到的word创建一个值(空列表)
                index[word].append(location)

    for word in sorted(index, key=str.upper):
        print(word, index[word])


Count_word('zen.txt')

 

推荐阅读