对文本中特定单词计数的函数中的递归



我对这段代码(python)进行递归有一个问题:

这是一个计算列表中单词个数的代码

def count_words(self, word):
count = 0
for line in self.lst:
if word.lower() in line.lower():
count += 1
return count

line在这里是一个变量,它包含这本书的句子

我需要让它递归,现在我有这样的代码:

def count_words_r(self, word, lst, count, length):
count = 0
if length < 1:
return count
else:
if word.lower() in line.lower():
length -= 1
count += 1
return 1 + self.count_words_r(word, lst, count, length)

这个代码的问题是变量line没有定义。

在这段代码中,文本被读取并保存在一个列表中

class Document:
def __init__(self, filename):
print("New Class")
text = open(filename, "r")
lst = []
for line in text.readlines():
if line not in ['n', '/ n','']:
lst.append(line[:-2])
print(lst[0:10])

self.lst = lst

我尝试在参数中定义变量line。

您没有提供明确的需求,并且您提供的代码不能被视为最小的,可重复的示例,因此这只是足够接近的东西,可以教会您为了实现目标所需要知道的内容。

# Count how many times "word" occurs in the list "list_of_words"
# The variable "count" is given the default value of zero and then
# the function passes the updated "count" back in when it calls itself
def count_words(word, list_of_words, count=0):
if list_of_words == []:
# We've processed the whole list. Break out of this recursive spiral
return count
# Pop out the last item in the list and store it as "this_word". 
# This makes the list smaller and eventually leads to the list 
# being equal to []   
# Example:
#    >>> mylist = ["foo", "bar", "baz"]
#    >>> popped = mylist.pop()
#    >>> mylist
#    ['foo', 'bar']
#    >>> popped
#    'baz'
this_word = list_of_words.pop()
# Is our word of interest equal to the word that we just popped?
if word == this_word:
count += 1
# Let's go again!!
return count_words(word,list_of_words,count)


words = "this is the end my only friend the end".split()
for word in words:
line = "it's the end of the world as we know it".split()  
print(f'count of "{word}" = {count_words(word,line)}') # Notice how we don't provide "count"?

输出:

count of "this" = 0
count of "is" = 1    
count of "the" = 2   
count of "end" = 1   
count of "my" = 0    
count of "only" = 0  
count of "friend" = 0
count of "the" = 2   
count of "end" = 1   

最新更新