首页 > 解决方案 > 无法在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'

请告知为什么第二个函数无法调用第一个函数?或者为什么我会收到这个错误?

标签: pythonfunctiondictionaryrandomattributeerror

解决方案


我必须做出一些假设,因为您遗漏了唯一重要的部分。

如果您尝试使您的示例更简单,您会看到这很可能是因为您分配给一个不返回任何内容,只打印的函数。

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

推荐阅读