2012-05-04 30 views
0

可能重複:
item frequency count in python如何查找單詞在數組中出現多少次? Python的

快速的問題

你如何找到一個字有多少次出現在一個陣列?

我有一個數組,有大約5000個單詞的文字,我想查找單詞「help」出現在數組中多少次。我該怎麼做呢?

的數組存儲在X,所以我的代碼如下所示:

x = [...] 
word = "help" 

,然後我不知道該怎麼把得到的時間「幫助」號出現在X

謝謝你的任何幫助!

+1

你到目前爲止嘗試過什麼?你可以向我們展示你現在使用的代碼,以便我們能夠更好地幫助你。 – Levon

+0

是5000個單詞中的每一個都是數組中的一個條目嗎? – cptPH

+0

我沒有嘗試過任何代碼,因爲我不知道我會怎麼做。 – Hoops

回答

5
>>> import collections 
>>> print collections.Counter(['a', 'word', 'is', 'a', 'thing', 'that', 'is', 'countable']) 
Counter({'a': 2, 'is': 2, 'word': 1, 'that': 1, 'countable': 1, 'thing': 1}) 

這是2.7+,一個Counter

根據您的修改,其中列表中的每個元素都是一個字母,而不是完整的單詞,然後:

>>> import re 
>>> letters = 
['i', 'n', 'e', 'e', 'd', 's', 'o', 'm', 'e', 'h', 'e', 'l', 'p', 'h', 'e', 'l', 'p', 'm', 'e', 'p', 'l', 'e', 'a', 's', 'e', 'I', 'n', 'e', 'e', 'd', 'h', 'e', 'l', 'p'] 
>>> len(re.findall('help', "".join(letters))) 
3 
+0

+1爲最乾淨和最強大的解決方案。如果這是一個家庭作業問題,那麼他仍然無法幫助他,他本來是要手動完成的。 :-) –

+0

我沒有認爲它是作業,因爲標籤不包括在內。但是,點了。 – sberry

1

由於@sberry已經描繪,計數器將服務器的目的,但如果你是僅搜索一次,沒興趣一字一句地獲得的所有單詞的發生,你可以用一個簡單的工具,給出的單詞的一個列表的目的

(我已經採取了從sberry的例子)

找到任何給定單詞的發生,你可以用列表的方法count

>>> list_of_words=['a', 'word', 'is', 'a', 'thing', 'that', 'is', 'countable'] 
>>> list_of_words.count('is') 
2 

因爲您的評論表明你可能有興趣的字符的列表上搜索。如

letters = 
['i', 'n', 'e', 'e', 'd', 's', 'o', 'm', 'e', 'h', 'e', 'l', 'p', 'h', 'e', 'l', 'p', 'm', 'e', 'p', 'l', 'e', 'a', 's', 'e', 'I', 'n', 'e', 'e', 'd', 'h', 'e', 'l', 'p'] 

您也可以使用該字符串的計數是通過連接所有字符

>>> ''.join(letters).count('help') 
3 

萬一的話是混亂產生後,collections.Counter廣告魔這裏

>>> def count_words_in_jumbled(jumbled,word): 
    jumbled_counter = collections.Counter(jumbled) 
    word_counter = collections.Counter(word) 
    return min(v /word_counter[k] for k,v in jumbled_counter.iteritems() if k in word) 

>>> count_words_in_jumbled(['h','e','l','l','h','e','l','l','h','e','l'],'hel') 
3 
>>> count_words_in_jumbled(['h','e','l','l','h','e','l','l','h','e','l'],'hell') 
2 
>>> count_words_in_jumbled(['h','x','e','y','l','u','p'] ,'help') 
1 
+0

-1 @Abhijit如果數組類似於'['h','x','e','y','l','u','p'],那麼join()方法將不起作用 –

+0

@AshwiniChaudhary:OP從未提到這些字母混亂。我也通讀了評論,但沒有提示相同的暗示。 – Abhijit

+0

它看起來像你是正確的,不能做+1我的投票被鎖定,直到你編輯解決方案。 –

0
nhelps = len(''.join(charlist).split('help')[1:] 
相關問題