如何在Python中递归地使用函数?

2024-04-26 22:18:34 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的bigrams程序。我输入一个文本文件“通道.txt“这个程序把摘录的内容做成一本字典。目标是从字典中选择一个键,打印它,然后查看它的值。它的值将具有与字典中其他键匹配的名称,因此随机选择一个值,并在相应的键上重复该过程,直到达到输入的字数。我可以打印第一个键和随机值的关键。我无法获取随机值,找到具有匹配值名称的字典键并重复该过程。你知道吗

import random

def getwords(file_name):
    with open(file_name, 'r') as file:
        text = file.read().lower()

    stop_letters = (".", ",", ";", ":", "'s", '"', "!", "?", "(", ")", '“', '”')
    text = ''.join([letter if letter not in stop_letters else '' for letter in text])

    words = text.split()
    return words


def compute_bigrams(fileName):
  input_list = getwords(fileName)
  bigram_list = {}
  for i in range(len(input_list) - 1):
    if input_list[i] in bigram_list:
      bigram_list[input_list[i]] = bigram_list[input_list[i]] + [input_list[i + 1]]
    else :
     bigram_list[input_list[i]] = [input_list[i + 1]]
  return bigram_list

wordReturn = int(input("How many words is your output?: "))
accessKey = int(input("Choose a key: "))

#Return key name from input and corresponding list
def generateBigramsText(fileName):
 bigrams = compute_bigrams(fileName)

 key = list(bigrams.keys())[accessKey]
 bigramWord =  bigrams[list(bigrams.keys())[accessKey]]

 return key , bigramWord

#Use Tuple to print key and random word from BigramWord list
def generateRandomText(fileName):
 bigram2 = generateBigramsText(fileName)
 thisKey = bigram2[0]
 newList = list(bigram2[1])
 nextWord = random.choice(newList)

 for x in range(wordReturn):
  thisKey = nextWord
  return thisKey

Tags: keytextnameininputreturn字典def