2013-03-06 132 views
0

重複我有這樣一個代碼:計數單詞的列表中的PYTHON

s = "hello this is hello this is baby baby baby baby hello" 
slist = s.split() 
finallist = [] 
for word in slist: 
    if len(word) >= 4: 
      final = final + [word] 

基本上這以上代碼,用於取列表,並僅把具有多於4個字符的單詞列表。

從這個列表中,我希望能夠統計同一單詞出現的次數並將其保存到新列表中。所以它會像[3,2,4] 3是你的時代,2是這個時代,4是嬰兒。

+1

我建議這樣的:HTTP:// docs.python.org/2/library/collections.html#collections.Counter – squiguy 2013-03-06 03:13:27

+0

看起來像作業。 – Demosthenex 2013-03-06 03:18:24

+0

@squiguy謝謝你這是我正在尋找的文檔。 – 2013-03-07 04:24:37

回答

3
from collections import Counter 
import re 

reg = re.compile('\S{4,}') 

s = "hello this is hello this is baby baby baby baby hello" 
c = Counter(ma.group() for ma in reg.finditer(s)) 
print c 

結果

Counter({'baby': 4, 'hello': 3, 'this': 2}) 

另外:

from collections import defaultdict 
d = defaultdict(int) 

s = "hello this is hello this is baby baby baby baby hello" 

for w in s.split(): 
    if len(w)>=4: 
     d[w] += 1 

print d 
+0

@Xaphen''re''是將正則表達式帶給我們處理的模塊。模式'''\ S {4,}'''表示'任何不同於空格的字符'''S'',這些字符的數量:4或更多。空格是''\ f'','''''''''''',''''''''''','''\ t'',''\ v'',''\ x''和空格。 ''re.finditer(s)''是在''s'中找到的匹配生成器,用於驗證模式。一個匹配''ma''內部保存信息:''ma.group()''是由''s''匹配的整個匹配部分組成的信息 – eyquem 2013-03-06 03:22:43

+0

@Xaphen謝謝。請注意,我使用了''re.finditer()'',因爲它是一個一個接一個地產生匹配的生成器,而不必象''re.findall()''一樣在迭代之前創建一個新對象。但是,如果字符串不是巨大的,它可能等同於編寫「Counter(reg.findall(text))」。如果這樣的研究不再重複,那麼regex對象''reg''不會再被使用,它也可以直接寫''Counter(re.findall('\ S {4,}'),text ))'' – eyquem 2013-03-07 10:31:28

3

collections.Counter顯然是你的朋友(除非你需要在一個特定的輸出的排序順序)。將它與生成器理解結合生成所有長度爲4的單詞,你是金。

from collections import Counter 

Counter(w for w in s.split() if len(w) >= 4) 

如果你需要的元素在他們的第一個出現的順序,使用有序字典:

from collections import OrderedDict 

wc = OrderedDict() 
for w in s.split(): 
    if len(w) >= 4: 
     wc[w] = wc.get(w, 0) + 1 
+0

簡單,直接,清晰。 – eyquem 2013-03-06 03:30:26

1

所有你需要做的就是使用count方法從SLIST。

我想你可以使用一個字典內有

s = "hello this is hello this is baby baby baby baby hello" 
slist = s.split() 
finaldict = {} 
for word in slist: 
    if len(word) >= 4 and not finaldict.get(word): 
      finaldict[word] = slist.count(word) 

更好的控制現在,如果你想要的值列表,只是這樣做:finallist = finaldict.values()

+0

...這不是很快,因爲你多次使用'.count'。 – nneonneo 2013-03-06 03:24:17

+0

@nneonneo每個字只使用一次計數。 – 2013-03-06 03:25:26

+0

@FernandoFreitasAlves:如果它是一個充滿獨特單詞的列表,那麼它真的很糟糕:) – nneonneo 2013-03-06 03:25:49