Python:如何找出列表中句子的出现次数

时间:2017-02-08 21:40:27

标签: python python-2.7 list

我正在编写一个函数来实现解决方案,以查找单词列表中出现单词的次数,从文本文件中检索,这非常简单易用。

但是,我已经花了两天时间试图弄清楚如何检查包含多个单词的字符串的出现次数,可以是两个或更多

所以例如说字符串是:

"hello bye"

,列表是:

["car", "hello","bye" ,"hello"]

该函数应返回值1,因为元素“hello”和“bye”仅连续出现一次。

我最接近解决方案的是使用

words[0:2] = [' '.join(words[0:2])]

在给定索引的情况下将两个元素连接在一起。然而这是错误的,因为给定的输入将是元素本身而不是索引。

有人能指出我正确的方向吗?

4 个答案:

答案 0 :(得分:1)

将字符串与主列表中连续元素的连接匹配。以下是示例代码:

grep

my_list = ["car", "hello","bye" ,"hello"] sentence = "hello bye" word_count = len(sentence.split()) c = 0 for i in range(len(my_list) - word_count + 1): if sentence == ' '.join(my_list[i:i+word_count]): c+=1 持有的最终价值为:

c

如果您正在寻找单行,可以使用>>> c 1 zip作为:

sum

答案 1 :(得分:1)

让我们将这个问题分成两部分。首先,我们建立一个函数,它将返回给定列表的 ngrams ,即n个连续元素的子列表:

def ngrams(l, n):
    return list(zip(*[l[i:] for i in range(n)]))

我们现在可以轻松获得2,3或4克:

>>> ngrams(["car", "hello","bye" ,"hello"], 2)
[('car', 'hello'), ('hello', 'bye'), ('bye', 'hello')]
>>> ngrams(["car", "hello","bye" ,"hello"], 3)
[('car', 'hello', 'bye'), ('hello', 'bye', 'hello')]
>>> ngrams(["car", "hello","bye" ,"hello"], 4)
[('car', 'hello', 'bye', 'hello')]

每个项目都被组成一个元组。

现在将短语'hello bye'变为元组:

>>> as_tuple = tuple('hello bye'.split())
>>> as_tuple
('hello', 'bye')
>>> len(as_tuple)
2

由于这有两个单词,我们需要从句子中生成双字母组,并计算匹配的双字母组的数量。我们可以将所有这些概括为

def ngrams(l, n):
    return list(zip(*[l[i:] for i in range(n)]))

def count_occurrences(sentence, phrase):
    phrase_as_tuple = tuple(phrase.split())
    sentence_ngrams = ngrams(sentence, len(phrase_as_tuple))
    return sentence_ngrams.count(phrase_as_tuple)

print(count_occurrences(["car", "hello","bye" ,"hello"], 'hello bye'))
# prints 1

答案 2 :(得分:1)

两种可能性。

## laboriously

lookFor = 'hello bye'
words = ["car", "hello","bye" ,"hello", 'tax', 'hello', 'horn', 'hello', 'bye']

strungOutWords = ' '.join(words)

count = 0
p = 0
while True:
    q = strungOutWords [p:].find(lookFor)
    if q == -1:
        break
    else:
        p = p + q + 1
        count += 1

print (count)

## using a regex

import re
print (len(re.compile(lookFor).findall(strungOutWords)))

答案 3 :(得分:0)

我建议将问题减少到计算另一个字符串中字符串的出现次数。

words = ["hello", "bye", "hello", "car", "hello ", "bye me", "hello", "carpet", "shoplifter"]
sentence = "hello bye"
my_text = " %s " % " ".join([item for sublist in [x.split() for x in words] for item in sublist])


def count(sentence):
    my_sentence = " %s " % " ".join(sentence.split())
    return my_text.count(my_sentence)


print count("hello bye")
>>> 2
print count("pet shop")
>>> 0