我需要定义一个名为freq_count(substr,list)
的函数。此函数接受str
和单词列表作为参数。它遍历单词列表并搜索每个单词并计算substr
中子字符串word
的出现次数。打印每个单词以及找到的子字符串出现次数。
这是我的代码:
def freq_count(substr,list):
start_po = 0
count = 0
for word in list:
if word.find(str(substr)) != -1:
start_po = word.find(str,start_po)
count = count + 1
return(str(word) + str(count))
答案 0 :(得分:0)
如果我理解正确,您必须迭代在words
列表和计数列表中每个单词的出现次数,然后打印出来
现在print
和return
是两个不同的任务。但是,上述语句已经为您要实现的功能定义了一个框架:
def freq_count(substr,list):
for word in list:
count = 0
while ...: #we find an occurence
count += 1
print(word+str(count))
我们仍然需要实现的唯一事情是发生检查。您已经通过使用find
方法部分解决了这个问题。唯一的问题是我们需要迭代,直到找不到更多的事件。因此,我们需要一个变量来跟踪我们当前在单词中的位置,我们称之为pos
的变量。 pos
添加到结构中,如下所示:
def freq_count(substr,list):
for word in list:
count = 0
pos = word.find(substr)
while pos >= 0:#we find an occurence
count += 1
pos += len(substr)
pos = word.find(substr,pos)
print(word+str(count))
这是如何工作的?我们第一次致电word.find(substr)
时,会在substr
中搜索word
的首次发现。如果不存在此类子字符串,pos
将等于-1
。在这种情况下,while
循环立即失败,因此不进行计数,在这种情况下结果为零。
在我们发现事件的情况下,pos
将等于子字符串开始的索引。我们增加了count
,因为我们发现了一次,我们更新pos
:首先我们添加子串len(substr)
的长度substr
,以防止我们再发现< em>部分重叠前一次出现。接下来我们再次致电find
,但现在我们将其作为开始位置pos
。因此,我们只查找稍后或pos
开始的事件。只要找到更多事件,while
循环就会重复循环。
演示(使用python3
):
>>> freq_count('aba',['','a','aba','ababa','abaaba','abababa','abacaba'])
0
a0
aba1
ababa1
abaaba2
abababa2
abacaba2