python - 无法在python中的函数内调用函数
问题描述
构建一个“模仿”字典,将文件中出现的每个单词映射到文件中紧跟该单词的所有单词的列表。单词列表可以按任何顺序排列,并且应该包括重复项。例如,键“and”可能具有列表 [“then”、“best”、“then”、“after”、...] 列出文本中“and”之后的所有单词。我们会说空字符串是文件中第一个单词之前的内容。
使用模仿字典,很容易发出模仿原始文本的随机文本。打印一个单词,然后查找接下来可能出现的单词并随机选择一个作为下一个工作。使用空字符串作为第一个单词来启动事物。如果我们遇到一个不在字典中的单词,请返回空字符串以保持内容移动。
定义第一个函数:
def mimic_dict(filename):
with open (filename, 'r+') as x:
x = x.read()
x = x.split()
dic = {}
for i in range(len(x)-1):
if x[i] not in doc:
dic[x[i]] = [x[i+1]]
else:
dic[x[i]].append(x[i+1])
print(dic)
mimic_dict('small.txt')
输出:
{'we': ['are', 'should', 'are', 'need', 'are', 'used'], 'are': ['not', 'not', 'not'], 'not': ['what', 'what', 'what'], 'what': ['we', 'we', 'we'], 'should': ['be'], 'be': ['we', 'but', 'football'], 'need': ['to'], 'to': ['be', 'be'], 'but': ['at'], 'at': ['least'], 'least': ['we'], 'used': ['to']}
定义第二个函数并在其中调用第一个函数
import random
def print_mimic(x):
l = []
for i in range(5):
word = random.choice(list(x.items()))
l.append(word)
print(l)
print_mimic(mimic_dict)
AttributeError Traceback (most recent call last)
<ipython-input-40-c1db7ba9ddae> in <module>
8
9 print(l)
---> 10 print_mimic(d)
<ipython-input-40-c1db7ba9ddae> in print_mimic(x)
4 l = []
5 for i in range(2):
----> 6 word = random.choice(list(x.items()))
7 l.append(word)
8
AttributeError: 'NoneType' object has no attribute 'items'
请告知为什么第二个函数无法调用第一个函数?或者为什么我会收到这个错误?
解决方案
我必须做出一些假设,因为您遗漏了唯一重要的部分。
如果您尝试使您的示例更简单,您会看到这很可能是因为您分配给一个不返回任何内容,只打印的函数。
def foo():
x = amazing_calculation()
print x
def bar(x):
print x
>>> y = foo()
amazing
>>> bar(y) # foo doesn't return anything, so 'y' is None
None
推荐阅读
- c# - C#如何使用互操作从多个工作表excel中读取指定的单元格?
- python - Python 3 SublimeText 3 与 open() 导致 FileNotFoundError
- python - data[2:2 * n + 2:2] 与下面的代码有关
- c# - ASMX 和 cs 参考
- javascript - async/await 返回 Promise {
} - javascript - 如何从反应js中的事件处理程序呈现父元素中的子元素
- swift - 无法遍历 SPTPlaylistList 项目
- pyspark - pyspark 将 DStreams 流式传输到 kafka 主题
- visual-c++ - 图像的旋转 DFT 真的与图像旋转的 DFT 相同吗?
- php - 空值的购物车数组会话