python - 如何在 Python 中递归地使用我的函数?
问题描述
这是我的二元组程序。我输入一个文本文件“Passage.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
解决方案
推荐阅读
- r - Shiny.io 无法部署应用程序
- c# - 当用户使用javascript单击单元格时如何显示数据?
- flutter - 如何在长按时将图像存储在 Firebase 中?我有一个图像列表视图
- java - Java中的正斜杠有什么用?
- python - 数据框中的 Python 时间戳 - 转换为数据格式
- javascript - Angular 通用函数处理程序不更新组件属性
- python-3.x - InvalidArgumentError 函数调用堆栈:train_function
- sql - SQL .如何查找具有几乎相同字符串值的记录?
- python - 我正在尝试创建一个代码,该代码能够计算一个人需要获得什么成绩才能获得理想的整体成绩
- windows-subsystem-for-linux - 在 WSL2 中安装 v4l2loopback