Как я генерирую многословные термины рекурсивно?

искать файл: application.properties

путь к файлу: / src / main / resources /

добавить строку:

server.port = 8090

, если вы хотите достичь случайного порта:

server.port = 0
5
задан tgray 1 April 2009 в 12:41
поделиться

4 ответа

Это не рекурсивно, но я думаю, что это делает то, что Вы хотите.

doc = 'a b c d e f'
words = doc.split(None)
max = 3          


for index in xrange(len(words)):    
    for n in xrange(max):
        if index + n < len(words):           
            print ' '.join(words[index:index+n+1])   

И вот рекурсивное решение:

def find_terms(words, max_words_per_term):       
    if len(words) == 0: return []
    return [" ".join(words[:i+1]) for i in xrange(min(len(words), max_words_per_term))] + find_terms(words[1:], max_words_per_term)


doc = 'a b c d e f'
words = doc.split(None) 
for term in find_terms(words, 3):
    print term

Вот рекурсивная функция снова с некоторыми переменными объяснения и комментариями.

def find_terms(words, max_words_per_term):   

    # If there are no words, you've reached the end. Stop.    
    if len(words) == 0:
        return []      

    # What's the max term length you could generate from the remaining 
    # words? It's the lesser of max_words_per_term and how many words 
    # you have left.                                                         
    max_term_len = min(len(words), max_words_per_term)       

    # Find all the terms that start with the first word.
    initial_terms = [" ".join(words[:i+1]) for i in xrange(max_term_len)]

    # Here's the recursion. Find all of the terms in the list 
    # of all but the first word.
    other_terms = find_terms(words[1:], max_words_per_term)

    # Now put the two lists of terms together to get the answer.
    return initial_terms + other_terms 
11
ответ дан 18 December 2019 в 09:10
поделиться

Я предложил бы, чтобы Вы сделали свою функцию генератором и затем генерировать требуемое количество условий. Необходимо было бы измениться print кому: yield (и сделайте целую функцию блока, очевидно).

Вы могли бы взглянуть на itertools модуль также, это довольно полезно для вида работы, которую Вы делаете.

3
ответ дан 18 December 2019 в 09:10
поделиться

Почему Вы делаете это? Можно вместо этого просто использовать для цикла и itertools.combinations().

3
ответ дан 18 December 2019 в 09:10
поделиться

Вы ищете алгоритм N-грама. Это даст вам [a,ab,b,bc,c,cd,...].

.
1
ответ дан 18 December 2019 в 09:10
поделиться
Другие вопросы по тегам:

Похожие вопросы: