慕課網 如何統計序列中元素的出現頻度

2021-08-17 02:21:45 字數 1047 閱讀 8491

from random import randint

import requests

from collections import counter

from lxml import etree

import re

'如何統計序列中元素的出現頻度'

# 從隨機字串中 找到次數最高的三個元素

def main():

data = [randint(0, 20) for _ in range(30)]

print(data)

c = dict.fromkeys(data, 0)

c2 = counter(data)

for x in data:

c[x] += 1

print("排序方案1:%s" % c)

print("排序方案2:%s出現的次數:%s" % (1, c2[1]))

print("頻數最高的3個元素%s" % c2.most_common(3))

pass

# 對文字進行詞頻統計

def main2():

# 可以複製直接用這個

# txt=open('/test05.py').read()

# 或者比較複雜 去讀取網上的文字

txt = requests.get("").text

text = etree.html(txt)

a = text.xpath('//*[@id="articlebody"]/p')

alltext = " "

for x in a:

if x.text is not none:

alltext = alltext + x.text + "\n "

alltext2=re.split('\w+',alltext)

c3=counter(alltext2)

print(c3)

print(c3.most_common(3))

pass

main2()

Python教程 如何統計序列中元素的出現頻度

實際操作中,我們該如何統計序列中元素的出現頻度,這篇python實戰教程手把手教你!實際案例 from random import randint 使用列表解析生成30個元素 在0 20範圍內 data randint 0,20 for in xrange 30 print type data 使用...

Python 統計序列中元素出現次數

import sys import random from collections import counter reload sys sys.setdefaultencoding utf 8 data list random.randint 1,20 for in range 10 從1 20隨機...

py程式設計技巧 1 3 如何統計序列中元素的出現頻度

實際案例 某隨機序列中,找到出現次數最高的三個元素,他們的出現次數是多少?對某英文文章的單詞進行詞頻統計,找到出現次數最高的10個單詞,出現次數是多少?from random import randint 使用列表解析生成30個元素 在0 20範圍內 data randint 0,20 for in...