Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法在python中的函数内调用函数_Python_Function_Dictionary_Random_Attributeerror - Fatal编程技术网

无法在python中的函数内调用函数

无法在python中的函数内调用函数,python,function,dictionary,random,attributeerror,Python,Function,Dictionary,Random,Attributeerror,构建一个模拟dict,映射文件中出现的每个单词 指向文件中紧跟该单词之后的所有单词的列表。 单词列表可以是任何顺序,并且应该包括 复制品。例如,键和可能有列表 [然后,最好,然后,…]上市 课文中跟在后面的所有单词。 我们会说空字符串是前面的字符串 文件中的第一个单词 使用模拟dict,很容易发出随机信号 模仿原文的文本。打印一个单词,然后查看 找出下一个可能出现的单词,然后随机选择一个作为 下一步工作。 使用空字符串作为第一个单词来初始化内容。 如果我们被一个不在格言中的词所困扰, 返回到空字

构建一个模拟dict,映射文件中出现的每个单词 指向文件中紧跟该单词之后的所有单词的列表。 单词列表可以是任何顺序,并且应该包括 复制品。例如,键和可能有列表 [然后,最好,然后,…]上市 课文中跟在后面的所有单词。 我们会说空字符串是前面的字符串 文件中的第一个单词

使用模拟dict,很容易发出随机信号 模仿原文的文本。打印一个单词,然后查看 找出下一个可能出现的单词,然后随机选择一个作为 下一步工作。 使用空字符串作为第一个单词来初始化内容。 如果我们被一个不在格言中的词所困扰, 返回到空字符串以使内容保持移动

定义第一个功能:

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)

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

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

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

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

非常感谢。我不知道我怎么会忽略这一点。python设计选择的副作用=。如果您在编辑器中运行一个linter,您将看到一些关于使用函数调用的结果的注释,该函数调用不返回值
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