Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.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 如何在文本文件中查找单词?_Python_File_Text_Word Frequency_Alphabetical Sort - Fatal编程技术网

Python 如何在文本文件中查找单词?

Python 如何在文本文件中查找单词?,python,file,text,word-frequency,alphabetical-sort,Python,File,Text,Word Frequency,Alphabetical Sort,我正在编写一个Python程序,我需要计算文本文件中每个单词的数量 def count_words(word,d): for l in word: if l in d: d[l] += 1 else: d[l] = 1 return d def count_letters(): d = dict() word_file = open('w.txt') for line

我正在编写一个Python程序,我需要计算文本文件中每个单词的数量

def count_words(word,d):
    for l in word:
        if l in d:
            d[l] += 1
        else:
            d[l] = 1
        return d

def count_letters():
    d = dict()
    word_file = open('w.txt')
    for line in word_file:
        word = line.strip();
        d = count_words(word,d)
    return d

如果其中一个条件是
int
,则通过对键函数中的
int
求反,可以轻松地在一个条件下进行反向排序,在另一个条件下进行正向排序

替换

freq_list.sort()

在更一般的情况下,由于Python的排序是,因此可以按第二个键排序,然后按第一个键排序

freq_list.sort(key=lambda x:x[0])
freq_list.sort(key=lambda x:x[1], reverse=True)

缺点是您需要进行两种排序,因此速度稍慢

lambda需要返回一个元组:
(-x[1],x[0])
这正是Python 3将这些不明确的构造视为非法的原因……它们对解释器来说并不模糊,但每次看到它们时,您都有50/50的机会将它们解释错误(或者编写看起来正确但会引发神秘错误的代码,如
TypeError:“tuple”对象在运行时不可调用
)。回答得好。要进一步阅读,请参阅文档中的。@gnibler感谢您的帮助!@gnibler您能看看我对程序所做的更改,看看我做错了什么吗?这是相同的概念,只是一个完全不同的外观,应该是这样的。
freq_list.sort(key=lambda x:x[0])
freq_list.sort(key=lambda x:x[1], reverse=True)