當前位置:首頁 » 編程語言 » counterpython

counterpython

發布時間: 2023-07-14 11:21:36

python中類的實例對象的理解總結

9.3.3. 實例對象
現在我們可以用實例對象作什麼?實例對象唯一可用的操作就是屬性引用。有兩種有效的屬性名。
數據屬性 相當於 Smalltalk 中的「實例變數」或 C++ 中的「數據成員」。和局部變數一樣,數據屬性不需要聲明,第一次使用時它們就會生成。例如,如果 x 是前面創建的 MyClass 實例,下面這段代碼會列印出 16 而在堆棧中留下多餘的東西:
x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print(x.counter)
del x.counter
另一種為實例對象所接受的引用屬性是 方法。方法是「屬於」一個對象的函數。(在 Python 中,方法不止是類實例所獨有:其它類型的對象也可有方法。例如,鏈表對象有 append,insert,remove,sort 等等方法。然而,在後面的介紹中,除非特別說明,我們提到的方法特指類方法)
實例對象的有效名稱依賴於它的類。按照定義,類中所有(用戶定義)的函數對象對應它的實例中的方法。所以在我們的例子中,x.f 是一個有效的方法引用,因為 MyClass.f 是一個函數。但 x.i 不是,因為 MyClass.i 不是函數。不過 x.f 和 MyClass.f 不同,它是一個 方法對象 ,不是一個函數對象。

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

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

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

❸ python collections counter的值怎麼取出來

使用counter類的items()函數即可,Python3程序如下:

foreachincount.items():#假設存在counter類的count
(a,b)=each
print(a,b.sep=' ',end=' ',file='./test.txt')

❹ python counter類的keys怎麼排序

(1)從Collections集合模塊中引入集合類Counter
(2)Counter(a)可以列印出數組a中每個元素出現的次數
(3)Counter(a).most_common(2)可以列印出數組中出現次數最多的元素。參數2表示的含義是:輸出幾個出現次數最多的元素。

❺ 如何用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

熱點內容
oracle定義存儲過程 發布:2025-02-08 16:54:35 瀏覽:147
mac玩飢荒要什麼配置 發布:2025-02-08 16:52:18 瀏覽:679
androidattributeset 發布:2025-02-08 16:51:23 瀏覽:422
c語言調用函數返回值 發布:2025-02-08 16:51:19 瀏覽:786
有壓縮錢嗎 發布:2025-02-08 16:34:01 瀏覽:517
折紙手工解壓小方塊 發布:2025-02-08 16:32:45 瀏覽:254
php與運算符 發布:2025-02-08 16:32:45 瀏覽:764
如何用伺服器搭建懸賞平台 發布:2025-02-08 16:29:53 瀏覽:280
ftp伺服器破解版 發布:2025-02-08 16:28:41 瀏覽:523
mysql配置訪問ip 發布:2025-02-08 16:22:49 瀏覽:116