前言

在看一个聊天机器人的神经网络模型训练前准备训练数据,需要对训练材料做处理(转化成张量)需要先提炼词干,然后对词干做去重和排序

words = sorted(list(set(words)))

对这三个方法做一下整理:

1.set()

语法:set([iterable])

参数:可迭代对象(可选),a sequence (string, tuple, etc.) or collection (list, set, dictionary, etc.) or an iterator object to be converted into a set

返回值:set集合

作用:去重,因为set集合的本质是无序,不重复的集合。所以转变为set集合的过程就是去重的过程

 # empty set
print(set()) # from string
print(set('google')) # from tuple
print(set(('a', 'e', 'i', 'o', 'u'))) # from list
print(set(['g', 'o', 'o', 'g', 'l', 'e'])) # from range print(set(range()))

运行结果:

set()
{'o', 'G', 'l', 'e', 'g'}
{'a', 'o', 'e', 'u', 'i'}
{'e', 'g', 'l', 'o'}
{, , , , }

2.sorted()

语法:sorted(iterable[, key][, reverse])

参数:

iterable 可迭代对象,- sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any iterator

reverse 反向(可选),If true, the sorted list is reversed (or sorted in Descending order)

key (可选),function that serves as a key for the sort comparison

返回值:a sorted list 一个排好序的列表

示例1:排序

# vowels list
pyList = ['e', 'a', 'u', 'o', 'i']
print(sorted(pyList)) # string
pyString = 'Python'
print(sorted(pyString)) # vowels tuple
pyTuple = ('e', 'a', 'u', 'o', 'i')
print(sorted(pyTuple))

结果:

['a', 'e', 'i', 'o', 'u']
['P', 'h', 'n', 'o', 't', 'y']
['a', 'e', 'i', 'o', 'u']

示例2:反向排序

# set
pySet = {'e', 'a', 'u', 'o', 'i'}
print(sorted(pySet, reverse=True)) # dictionary
pyDict = {'e': , 'a': , 'u': , 'o': , 'i': }
print(sorted(pyDict, reverse=True)) # frozen set
pyFSet = frozenset(('e', 'a', 'u', 'o', 'i'))
print(sorted(pyFSet, reverse=True))

结果:

['u', 'o', 'i', 'e', 'a']
['u', 'o', 'i', 'e', 'a']
['u', 'o', 'i', 'e', 'a']

示例3:指定key parameter排序

 # take second element for sort
def takeSecond(elem):
return elem[] # random list
random = [(, ), (, ), (, ), (, )] # sort list with key
sortedList = sorted(random, key=takeSecond) # print list
print('Sorted list:', sortedList)

结果:

Sorted list: [(, ), (, ), (, ), (, )]

值得一提的是,sort()和sorted()的区别:

sort 是应用在 list 上的方法(list.sort()),sorted 可以对所有可迭代的对象进行排序操作(sorted(iterable))。
list 的 sort 方法返回的是对已经存在的列表进行操作,无返回值,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。

在了解这几个函数的过程中,发现了一个博友的文章,关于校招题目的,摘其中一道题如下:

原文链接:http://www.cnblogs.com/klchang/p/4752441.html

用python实现统计一篇英文文章内每个单词的出现频率,并返回出现频率最高的前10个单词及其出现次数,并解答以下问题?(标点符号可忽略)

答案如下:

 def findTopFreqWords(filename, num=):
'Find Top Frequent Words:'
fp = open(filename, 'r')
text = fp.read()
fp.close() lst = re.split('[0-9\W]+', text) # create words set, no repeat
words = set(lst)
d = {}
for word in words:
d[word] = lst.count(word)
del d[''] result = []
for key, value in sorted(d.iteritems(), key=lambda (k,v): (v,k),reverse=True):
result.append((key, value))
return result[:num] def test():
topWords = findTopFreqWords('test.txt',)
print topWords if __name__=='__main__':
test()

使用的 test.txt 内容如下,

3.1   Accessing Text from the Web and from Disk

Electronic Books

A small sample of texts from Project Gutenberg appears in the NLTK corpus collection.
However, you may be interested in analyzing other texts from Project Gutenberg.
You can browse the catalog of 25,000 free online books at http://www.gutenberg.org/catalog/, and obtain a URL to an ASCII text file.
Although 90% of the texts in Project Gutenberg are in English, it includes material in over 50 other languages, including Catalan, Chinese, Dutch, Finnish, French, German, Italian,

  

python中sorted()和set()去重,排序的更多相关文章

  1. Python中sorted()方法

    Python中sorted()方法的用法 1.先说一下iterable,中文意思是迭代器. Python的帮助文档中对iterable的解释是:iteralbe指的是能够一次返回它的一个成员的对象.i ...

  2. Python中sorted()方法的用法

    Python中sorted()方法的用法 2012-12-24 22:01:14|  分类: Python |字号 订阅 1.先说一下iterable,中文意思是迭代器. Python的帮助文档中对i ...

  3. Python中sorted(iterable, /, *, key=None, reverse=False)的参数中的斜杆是什么意思?

    通过help(sorted)查看sorted的帮助文档,显示如下: Help on built-in function sorted in module builtins: sorted(iterab ...

  4. python 中 sorted() 和 list.sort() 的用法

    今天用python自带的sorted对一个列表进行排序, 在这里总结一下 只要是可迭代对象都可以用sorted . sorted(itrearble, cmp=None, key=None, reve ...

  5. [转].Python中sorted函数的用法

    [Python] sorted函数 我们需要对List.Dict进行排序,Python提供了两个方法对给定的List L进行排序,方法1.用List的成员函数sort进行排序,在本地进行排序,不返回副 ...

  6. python中sorted方法和列表的sort方法使用详解

    一.基本形式 列表有自己的sort方法,其对列表进行原址排序,既然是原址排序,那显然元组不可能拥有这种方法,因为元组是不可修改的. 排序,数字.字符串按照ASCII,中文按照unicode从小到大排序 ...

  7. Python中sorted函数的用法(转)

    [Python] sorted函数 我们需要对List.Dict进行排序,Python提供了两个方法 对给定的List L进行排序, 方法1.用List的成员函数sort进行排序,在本地进行排序,不返 ...

  8. python中sorted方法和列表的sort方法使用

    一.基本形式 列表有自己的sort方法,器对列表进行原值排序,既然是原址排序,那显然元组不可能拥有这个方法,因为元组是不可修改的. 排序,数字.字符串按照ASCII,中文按照unicode从小到大排序 ...

  9. Python 中 sorted 如何自定义比较逻辑

    在 Python 中对一个可迭代对象进行排序是很常见的一个操作,一般会用到 sorted() 函数 num_list = [4, 2, 8, -9, 1, -3] sorted_num_list = ...

随机推荐

  1. jquery复制图片

    <div class="img-div">           <a href="javascript:void(0);"><im ...

  2. [LeetCode] Smallest Rotation with Highest Score 得到最高分的最小旋转

    Given an array A, we may rotate it by a non-negative integer K so that the array becomes A[K], A[K+1 ...

  3. 在 CentOS7 安装 ELK

    ELK是一个成熟的日志系统,主要功能有收集.分析.检索,详细见 elastic官网. 本文主要介绍如何在CentOS7下安装最新版本的ELK,当然现在docker已经有完全配置成功的elk容器,安装配 ...

  4. hdfs OutOfMemoryError

    大量推送本地文件到hdfs如下 hadoop fs -put ${local_path} ${hdfs_path}报错. Exception in thread "main" ja ...

  5. 配置ssh框架启动tomcat服务器报异常Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

    在Spring中配置jdbc时,引用的是dbcp.jar包,在db.properties配置文件中,使用了之前的properties配置文件的用户名username(MySql用户名) 然后在启动服务 ...

  6. 问题:怎么把mysql的系统时间调整为电脑的时间?(已解决)

    我的mysql是5.7版本. 浏览mysql的错误日志的时候,发现时间和电脑时间不一致. 查了一下,知道这个时间和log_timestamps有关, 就在mysql里执行下面一句话: SET GLOB ...

  7. Troubleshooting tips for using Java on Windows 8

    This article applies to: Platform(s): Windows 8 Will Java run in Start screen on Windows 8? Microsof ...

  8. vue 实现子向父传值

    父组件 <template> <div id="app"> <child @onChange='onChildValue'></child ...

  9. Kali 开启 SSH 服务方法

    尝试了开启kali的ssh,方法如下: 1.修改sshd_config文件.命令:vim /etc/ssh/sshd_config 2.将#PasswordAuthentication no的注释去掉 ...

  10. windows 下使用 protobuf

    下载protobuf 下载地址:https://github.com/google/protobuf/releases 选择protoc-xxx-win32.zip下载 配置环境变量 将解压出来的pr ...