【问题标题】:How to find how many times a word appears in a array? Python [duplicate]如何找到一个单词在数组中出现的次数? Python [重复]
【发布时间】:2012-05-13 16:05:51
【问题描述】:

可能重复:
item frequency count in python

快速提问

如何找出一个单词在数组中出现的次数?

我有一个包含大约 5000 字文本的数组,我想找出“帮助”一词在数组中出现的次数。我该怎么做?

数组存储在x中,所以我的代码如下所示:

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

然后我不知道该放什么来获得“帮助”出现在 x 中的次数

感谢您的帮助!

【问题讨论】:

  • 到目前为止您尝试过什么?您能否向我们展示您目前拥有的代码,以便我们更好地帮助您。
  • 这 5000 个单词中的每一个都是数组中的一个条目吗?
  • 我没有尝试过任何代码,因为我不知道该怎么做。
  • 数组就像['h', 'e', 'l', 'l', 'o'....等]
  • 查看这里给出的答案stackoverflow.com/questions/893417/…

标签: python arrays


【解决方案1】:
>>> 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

【讨论】:

  • +1 获得最干净、最强大的解决方案。如果这是一个家庭作业问题并且他打算手动完成,那仍然对他没有多大帮助。 :-)
  • 我不认为这是家庭作业,因为标签不包括在内。但是,重点。
【解决方案2】:

正如@sberry 所描述的那样,Counter 会达到目的,但如果您只搜索一个单词并且不希望获得所有单词的出现,您可以使用更简单的工具来达到目的

(我以 sberry 为例)

给定一个单词列表来查找任何给定单词的出现,可以使用列表的count方法

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

正如您的 cmets 所显示的,您可能有兴趣在字符列表中进行搜索。比如

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

【讨论】:

  • -1 @Abhijit 如果数组类似于['h','x','e','y','l','u','p'],则join() 方法将不起作用
  • @AshwiniChaudhary:OP 从未提到这些字母是混乱的。我也通读了 cmets,但没有一点提示。
  • 看来你是对的,在你编辑解决方案之前无法 +1 我的投票被锁定。
  • @AshwiniChaudhary:我已经编辑了我的答案。检查它的最后一部分:-)
  • 投反对票的原因是什么?
【解决方案3】:
nhelps = len(''.join(charlist).split('help')[1:]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多