python - 如何翻字典 "inside-out"

标签 python dictionary

免责声明:我才刚刚开始学习 Python

我有一个函数,可以计算一个单词在文本文件中出现的次数,并将该单词设置为键,将计数设置为值,并将其存储在字典“book_index”中。这是我的代码:

alice = open('location of the file', 'r', encoding = "cp1252")

def book_index(alice):
    """Alice is a file reference"""
    """Alice is opened, nothing else is done"""
    worddict = {}
    line = 0

    for ln in alice:
        words = ln.split()
        for wd in words:
            if wd not in worddict:
                worddict[wd] = 1 #if wd is not in worddict, increase the count for that word to 1
            else:
                worddict[wd] = worddict[wd] + 1 #if wd IS in worddict, increase the count for that word BY 1
        line = line + 1
    return(worddict)

我需要将字典“翻个底朝天”,并使用计数作为键,将任何出现 x 次的单词作为值。例如:[2, 'hello', 'hi'] 其中 'hello' 和 'hi' 在文本文件中出现了两次。

我需要循环遍历我现有的字典还是再次循环遍历文本文件?

最佳答案

由于字典是值映射的键,因此您无法有效地按值进行过滤。因此,您将必须遍历字典中的所有元素以获取值具有特定值的键。

这将打印出字典 d 中值等于 searchValue 的所有键:

for k, v in d.items():
    if v == searchValue:
        print(k)

关于您的 book_index 函数,请注意您可以使用内置的 Counter用于计数。 Counter 本质上是一个字典,它将计数作为其值并自动处理不存在的键。使用计数器,您的代码将如下所示:

from collections import Counter
def book_index(alice):
    worddict = Counter()
    for ln in alice:
        worddict.update(ln.split())
    return worddict

或者,正如 roippi 在对另一个答案的评论中建议的那样,只需 worddict = Counter(word for line in alice for word in line.split())

关于python - 如何翻字典 "inside-out",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19962586/

相关文章:

python - 编译成字节码占用太多内存

dictionary - Flutter ExpansionTile child 作为 Gridview?

python - Pandas Dataframe reshape ,通过将列转换为列索引,但保持列索引的其余部分不变

python - PyGObject 模板子项未定义

python - 如何定义多个数据框

objective-c - 从另一个应用程序转到 iPhone map 应用程序

python - 搭建python与smalltalk通信的桥梁

python - 如何为霍夫曼编码和解码创建一棵树?

python - 来自 df 的字典,键内有列

python - 使用键作为标题和值作为列将字典写入 csv 时出现问题