導航:首頁 > 編程語言 > pythoncounter下載

pythoncounter下載

發布時間:2023-03-07 01:20:14

A. python中的count函數問題


統計一個列表中每一個元素的個數在Python里有兩種實現方式,

第一種是新建一個dict,鍵是列表中的元素,值是統計的個數,然後遍歷list。

items=["cc","cc","ct","ct","ac"]
count={}
foriteminitems:
count[item]=count.get(item,0)+1
print(count)
#{'ac':1,'ct':2,'cc':2}

之中用到了一個小技巧,當dict中不還沒有統計過一個元素時,直接索引count[item]會報錯,而使用get方法count.get(item, 0)能夠設置索引不存在的鍵時返回0。


第二種是使用Python內置的函數。統計元素的個數是一種非常常見的操作,Python的collection包里已經有一個Counter的類,大致實現了上面的功能。

fromcollectionsimportCounter
items=["cc","cc","ct","ct","ac"]
count=Counter(items)
print(count)
#Counter({'ct':2,'cc':2,'ac':1})

B. 用Python編寫程序,輸入16個整數,輸出其中出現了多少個相同的數字要求輸入:一

代碼:

from collections import Counter
a = []
for i in range(16):
a.append(int(input("input score:"))) #注意縮進,網路太對代碼太不友好了

b = dict(Counter(a))
print ("repeated nums:(value:count)")
print ({key:value for key,value in b.items()if value > 1})

輸出:
input score:1
input score:2
input score:3
input score:4
input score:5
input score:6
input score:7
input score:8
input score:9
input score:10
input score:10
input score:9
input score:9
input score:8
input score:7
input score:7
repeated nums:(value:count)
{8: 2, 9: 3, 10: 2, 7: 3}

C. Python 統計列表裡面有多少個元素

Python 統計列表裡面有多少個元素步驟如下:

1、打開python語言命令窗口,定義一個列表變數Z並列印對應的列表值。

D. 如何用python實現英文短文的雙詞頻統計

簡單版:

#!/usr/bin/envpython3
importre
importjieba
fromcollectionsimportCounter

fname='counttest.txt'
withopen(fname)asf:
s=f.read()
pattern=re.compile(r'[a-zA-Z]+-?[a-zA-Z]*')
english_words=Counter(pattern.findall(s))
other_words=Counter(jieba.cut(pattern.sub('',s)))
print(' 英文單詞統計結果: '+'-'*17)
print(' '.join(['{}:{}'.format(i,j)fori,jinenglish_words.most_common()]))
print(' 中文及符號統計結果: '+'-'*19)
print(' '.join(['{}:{}'.format(i,j)fori,jinother_words.most_common()]))

復雜版:

#!/usr/bin/envpython
#-*-coding:utf-8-*-
from__future__importprint_function,division,unicode_literals
importsys,re,time,os,jieba
fromcollectionsimportCounter
fromdatetimeimportdatetime

classWordCounter(object):
def__init__(self,from_file,to_file=None,coding=None,jieba_cut=None):
'''根據設定的進程數,把文件from_file分割成大小基本相同,數量等同與進程數的文件段,
來讀取並統計詞頻,然後把結果寫入to_file中,當其為None時直接列印在終端或命令行上。
Args:
@from_file要讀取的文件
@to_file結果要寫入的文件
@coding文件的編碼方式,默認為採用chardet模塊讀取前1萬個字元來自動判斷
@jieba_cut是否啟用結巴分詞,默認為None

Howtouse:
w=WordCounter('a.txt','b.txt')
w.run()
'''
ifnotos.path.isfile(from_file):
raiseException('Nosuchfile:文件不存在')
self.f1=from_file
self.filesize=os.path.getsize(from_file)
self.f2=to_file

ifcodingisNone:
try:
importchardet
exceptImportError:
os.system('pipinstallchardet')
print('-'*70)
importchardet
withopen(from_file,'rb')asf:
coding=chardet.detect(f.read(10000))['encoding']
self.coding=coding
self._c=[Counter(),Counter()]
self.jieba=False
ifjieba_cutisnotNone:
self.jieba=True

defrun(self):
start=time.time()
if1:
self.count_direct(self.f1)
ifself.f2notin['None','Null','none','null',None]:
withopen(self.f2,'wb')asf:
f.write(self.result.encode(self.coding))
else:
print(' Englishwords: '+'-'*15)
print(self.result)
cost='{:.1f}'.format(time.time()-start)
size=humansize(self.filesize)
tip=' Filesize:{}.Costtime:{}seconds'
#print(tip.format(size,cost))
self.cost=cost+'s'

defcount_direct(self,from_file):
'''直接把文件內容全部讀進內存並統計詞頻'''
start=time.time()
withopen(from_file,'rb')asf:
line=f.read()
foriinrange(len(self._c)):
self._c[i].update(self.parse(line)[i])


defparse(self,line):#解析讀取的文件流
text=line.decode(self.coding)
text=re.sub(r'- ','',text)#考慮同一個單詞被分割成兩段的情況,刪除行末的-號
pattern=re.compile(r'[a-zA-Z]+-?[a-zA-Z]*')#判斷是否為英文單詞
english_words=pattern.findall(text)
rest=pattern.sub('',text)
ex=Counter(jieba.cut(rest))ifself.jiebaelseCounter(text)
returnCounter(english_words),ex

defflush(self):#清空統計結果
self._c=[Counter(),Counter()]

@property
defcounter(self):#返回統計結果的Counter類
returnself._c

@property
defresult(self):#返回統計結果的字元串型式,等同於要寫入結果文件的內容
ss=[]
forcinself._c:
ss.append(['{}:{}'.format(i,j)fori,jinc.most_common()])

tip=' 中文及符號統計結果: '+'-'*15+' '
returntip.join([' '.join(s)forsinss])

defhumansize(size):
"""將文件的大小轉成帶單位的形式
>>>humansize(1024)=='1KB'
True
>>>humansize(1000)=='1000B'
True
>>>humansize(1024*1024)=='1M'
True
>>>humansize(1024*1024*1024*2)=='2G'
True
"""
units=['B','KB','M','G','T']
forunitinunits:
ifsize<1024:
break
size=size//1024
return'{}{}'.format(size,unit)

defmain():
iflen(sys.argv)<2:
print('Usage:pythonwordcounter.pyfrom_fileto_file')
exit(1)
from_file,to_file=sys.argv[1:3]
args={'coding':None,'jieba_cut':1}
foriinsys.argv:
forkinargs:
ifre.search(r'{}=(.+)'.format(k),i):
args[k]=re.findall(r'{}=(.+)'.format(k),i)[0]
w=WordCounter(from_file,to_file,**args)
w.run()


if__name__=='__main__':
importdoctest
doctest.testmod()
main()

更復雜的:如果是比較大的文件,建議採用多進程,詳情網路:多進程讀取大文件並統計詞頻 jaket5219999

閱讀全文

與pythoncounter下載相關的資料

熱點內容
phparrayrecursive 瀏覽:708
天狼程序麻將機app怎麼下載 瀏覽:891
多行文字命令里怎麼弄每行三個字 瀏覽:556
方舟mod伺服器是什麼 瀏覽:987
怎麼下載智悲佛網的app 瀏覽:31
android地面站 瀏覽:482
apexsteam伺服器連接失敗怎麼辦 瀏覽:77
空調制熱外機風扇轉的慢壓縮機響 瀏覽:76
單片機為什麼有蜂鳴聲 瀏覽:761
windowsdos目錄命令 瀏覽:38
html博客源碼下載 瀏覽:113
android內核版本獲取 瀏覽:222
省錢app怎麼樣 瀏覽:586
活塞式壓縮機的優點 瀏覽:173
Android登錄記住狀態 瀏覽:632
雲伺服器狀態異常 瀏覽:345
bock壓縮機 瀏覽:569
登陸蘋果6伺服器出錯什麼原因 瀏覽:737
北漂程序員一個月多少錢 瀏覽:801
空調壓縮機呲呲聲 瀏覽:783