Python小技巧

1.Counter

from collections import Counter

a = [1,1,1,2,4,4,7,7,7,7,7]

x = Counter(a)

print(x)

x = Counter(a).most_common(2)

print(x)


运行结果

Counter(LIST)可以用于统计一个list中,相同元素出现的次数,例如运行结果的第一行,元素”7“在list a中出现了5次,元素”1“在list a 中出现了3次,以此类推。

Counter(LIST).most_common(k):用于统计出LIST中频数最多的k个元素,如运行结果的第二行,在一个数组里存放了元组,每个元祖代表一个元素与其频数。

2.MAP

map() 会根据提供的函数对指定序列做映射。第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

def dispose(x):

    return x+1

result = list(map(dispose,[1,2,3]))

print(result)


运行结果

3.返回一个文件的所有中文词汇(数据清洗+分词)


def getWordsFromFile(txtFile):#获取文件中的所有单词并返回

    words = list()

    with open(txtFile,encoding='utf-8') as fp:

        for line in fp:

            line = line.strip()

            line = sub(r'[.\[\]0-9、-。——,!~\*]','',line)

            line = cut(line)

            line = filter(lambda word:len(word)>1,line)

            words.extend(line)

    return words

你可能感兴趣的:(Python小技巧)