Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 循环浏览字典,找出7个最常见的单词。但前提是这些词不是';在另一个列表中找不到_Python - Fatal编程技术网

Python 循环浏览字典,找出7个最常见的单词。但前提是这些词不是';在另一个列表中找不到

Python 循环浏览字典,找出7个最常见的单词。但前提是这些词不是';在另一个列表中找不到,python,Python,我正在学习一些基本的Python3,并且已经被这个问题困扰了两天了,我似乎什么地方都做不到…… 我一直在读《思考python》这本书,我正在研究第13章及其包含的案例研究。这一章是关于阅读一个文件并用它做一些魔术,比如计算单词总数和最常用的单词。 程序的一部分是关于“字典减法”,程序从一个文本文件中提取另一个文本文件中找不到的所有单词 我还需要程序计算第一个文件中最常见的单词,不包括“dictionary”文本文件中的单词。这个功能让我卡住了两天,我真的不知道如何解决这个问题 我的程序的代码如下

我正在学习一些基本的Python3,并且已经被这个问题困扰了两天了,我似乎什么地方都做不到……
我一直在读《思考python》这本书,我正在研究第13章及其包含的案例研究。这一章是关于阅读一个文件并用它做一些魔术,比如计算单词总数和最常用的单词。
程序的一部分是关于“字典减法”,程序从一个文本文件中提取另一个文本文件中找不到的所有单词

我还需要程序计算第一个文件中最常见的单词,不包括“dictionary”文本文件中的单词。这个功能让我卡住了两天,我真的不知道如何解决这个问题

我的程序的代码如下所示:

import string

def process_file(filename):
  hist = {}
  fp = open(filename)


for line in fp:
    process_line(line, hist)
return hist


def process_line(line, hist):
    line = line.replace('-', ' ')

    for word in line.split():
        word = word.strip(string.punctuation + string.whitespace)
        word = word.lower()

        hist[word] = hist.get(word, 0) + 1


def most_common(hist):
    t = []
    for key, value in hist.items():
        t.append((value, key))

    t.sort()
    t.reverse()
    return t


def subtract(d1, d2):
    res = {}
    for key in d1:
        if key not in d2:
            res[key] = None
    return res


hist = process_file('alice-ch1.txt')
words = process_file('common-words.txt')
diff = subtract(hist, words)


def total_words(hist):
    return sum(hist.values())


def different_words(hist):
    return len(hist)


if __name__ == '__main__':

print ('Total number of words:', total_words(hist))
print ('Number of different words:', different_words(hist))

t = most_common(hist)
print ('The most common words are:')
for freq, word in t[0:7]:
    print (word, '\t', freq)
print("The words in the book that aren't in the word list are:")
for word in diff.keys():
    print(word)
然后,我创建了一个测试dict,其中包含一些单词和它们出现的假想时间,以及一个测试列表来尝试解决我的问题,代码是:

histfake = {'hello': 12, 'removeme': 2, 'hi': 3, 'fish':250, 'chicken':55, 'cow':10, 'bye':20, 'the':93, 'she':79, 'to':75}
listfake =['removeme', 'fish']

newdict = {}
for key, val in histfake.items():
    for commonword in listfake:
        if key != commonword:
            newdict[key] = val
        else:
            newdict[key] = 0

sortcommongone = []
for key, value in newdict.items():
    sortcommongone.append((value, key))
sortcommongone.sort()
sortcommongone.reverse()

for freq, word in sortcommongone:
    print(word, '\t', freq)
问题是,该代码只适用于一个单词。dict和列表之间只有一个匹配的单词的值为0(我想我可以给重复的单词赋值为0,因为我只需要在common word文本文件中找不到的7个最常见的单词。

我如何解决这个问题?在这里创建一个帐户只是为了尝试获得一些帮助,因为Stackowerflow以前在其他问题上帮助过我。但是这次我需要自己问这个问题。谢谢!

您可以使用
dict
来筛选项目

>>> {key: value for key, value in histfake.items() if key not in listfake}
{'hi': 3, 'she': 79, 'to': 75, 'cow': 10, 'bye': 20, 'chicken': 55, 'the': 93, 'hello': 12}
除非listfake大于histfake,否则最有效的方法是删除其中的键listfake

列表理解的复杂性和这个解决方案是O(n)-但是列表应该比字典短得多

编辑: 或者可以这样做-如果你有比实际单词更多的键- 对于输入密码: 如果输入listfake: del histfake[键] 你可能想

然后,当然,您必须将字典排序到列表中,并重新创建它

from operator import itemgetter    
most_common_7 = dict(sorted(histfake.items(), key=itemgetter(1))[:7])

顺便说一句,你可以用它来计算字数。也许你的部分问题是你没有从文本中删除所有非字母字符

谢谢你的回复!好吧,尝试再次检查的真正列表是一个文本文件,有1000行,每行一个单词。另一个文件只有200行,包含爱丽丝梦游仙境中的一章。因此,在我真正的文件问题中,我猜列表比真正的字典长。当我尝试您的代码时,我遇到了一个错误,itemgetter没有定义。它是需要导入的东西还是应该预定义为某个东西?尽管当我使用相同的技术(使用sortcommongone)对它进行排序时,就像我在原始回答文章中所做的那样,我得到了虽然当我用文本文件和“real”创建的“real”字典尝试你的解决方案时从common words文件创建的列表不再工作。我得到错误:TypeError uneatable type:“list”。即使我尝试将common words文件缩短为3个单词,我也会遇到此错误。猜测问题是该文件不可写?@Dan,我最初没有测试我的解决方案。但它确实工作。我一直怀疑您的这个问题在某种程度上与您处理文件中数据的方式有关。我通过删除整个代码来解决这个问题,并将问题提交给了我的大学课堂论坛。谢谢您的帮助!:)谢谢您的回复!如果我遵循您的代码,它将在我的示例中使用histfake和listfake。虽然如果我尝试将此解决方案应用于2个文本文件的实际问题,但它不起作用。它仍然打印出出现最多的单词是“the”和“she”,这两个单词都是文本文件中的单词,程序应该在计数中排除它们
from operator import itemgetter    
most_common_7 = dict(sorted(histfake.items(), key=itemgetter(1))[:7])