Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.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
File 为文件中的单词创建字典的函数_File_Function_Python 2.7_Dictionary - Fatal编程技术网

File 为文件中的单词创建字典的函数

File 为文件中的单词创建字典的函数,file,function,python-2.7,dictionary,File,Function,Python 2.7,Dictionary,我试图创建一个函数,它为特定文件中的每个单词向字典添加一个新键,并作为其值添加该单词后面的每个单词的列表。 我的代码不工作的原因我不明白。这是: def mimica(input_file): d = {} f = open(input_file) w = f.read().split() f.close() a = len(w) for i in range(0, a): word = [] b = i + 1

我试图创建一个函数,它为特定文件中的每个单词向字典添加一个新键,并作为其值添加该单词后面的每个单词的列表。 我的代码不工作的原因我不明白。这是:

def mimica(input_file):
    d = {}
    f = open(input_file)
    w = f.read().split()
    f.close()
    a = len(w)
    for i in range(0, a):
        word = []
        b = i + 1
        for a in range(b, a):
            word.append(w[a])
        d[w[i]] = word
    return d
这是我的文件的内容:

Car yellow and fast
Toy black and fun
Person tall and nice
这是我函数的输出:

{'and': [], 'Toy': ['black', 'and', 'fun'], 'Car': ['yellow', 'and', 'fast', 'Toy', 'black', 'and', 'fun', 'Person', 'tall', 'and', 'nice'], 'fast': ['Toy', 'black', 'and', 'fun', 'Person'], 'Person': [], 'black': ['and'], 'yellow': ['and', 'fast', 'Toy', 'black', 'and', 'fun', 'Person', 'tall', 'and'], 'fun': [], 'tall': [], 'nice': []}
谢谢你的帮助

    for a in range(b, a):
您正在使用此循环覆盖
a
的上一个值。尝试将名称更改为其他名称

    for x in range(b, a):
        word.append(w[x])
结果:

{
    'Car': ['yellow', 'and', 'fast', 'Toy', 'black', 'and', 'fun', 'Person', 'tall', 'and', 'nice'], 
    'yellow': ['and', 'fast', 'Toy', 'black', 'and', 'fun', 'Person', 'tall', 'and', 'nice'], 
    'fast': ['Toy', 'black', 'and', 'fun', 'Person', 'tall', 'and', 'nice'], 
    'Toy': ['black', 'and', 'fun', 'Person', 'tall', 'and', 'nice'], 
    'black': ['and', 'fun', 'Person', 'tall', 'and', 'nice'], 
    'fun': ['Person', 'tall', 'and', 'nice'], 
    'Person': ['tall', 'and', 'nice'], 
    'tall': ['and', 'nice'], 
    'and': ['nice'], 
    'nice': []
}

(为了清晰起见,我添加了空格)

是否正确,在
和“
后面不只是
“nice”
?毕竟,它出现得更早,后面跟着很多单词。@tobias_k,这是对问题陈述的一种可能解释。如果是这样,OP可以在循环的开始处将w[i]放入d:continue,以防止单词的后续实例覆盖早期实例。