Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.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_Python 3.x - Fatal编程技术网

Python 将附加值作为列表添加到字典值

Python 将附加值作为列表添加到字典值,python,python-3.x,Python,Python 3.x,这是我的密码: def corpus_reading_pos(corpus_name, pos_tag, option="pos"): pos_tags = [] words = [] tokens_pos = {} file_count = 0 for root, dirs, files in os.walk(corpus_name): for file in files: if file.endswith(".v

这是我的密码:

def corpus_reading_pos(corpus_name, pos_tag, option="pos"):
    pos_tags = []
    words = []
    tokens_pos = {}
    file_count = 0
    for root, dirs, files in os.walk(corpus_name):
        for file in files:
            if file.endswith(".v4_gold_conll"):
                with open((os.path.join(root, file))) as f:
                    pos_tags += [line.split()[4] for line in f if line.strip() and not line.startswith("#")]
                with open((os.path.join(root, file))) as g:
                    words += [line.split()[3] for line in g if line.strip() and not line.startswith("#")]
                    file_count += 1
    for pos in pos_tags:
        tokens_pos[pos] = []
    words_pos = list(zip(words, pos_tags))
    for word in words_pos:
        tokens_pos[word[1]] = word[0]
    #print(words_pos)
    print(tokens_pos)
    #print(words)
    print("Token count:", len(tokens_pos))
    print("File count:", file_count)
我试图创建一个字典,它把所有的词条作为键,字典值将是属于那个特定词条的所有单词。我在字典中的值上停留在一个值上,我必须创建一个单词表,但我似乎不能达到。
在代码中,行tokens_pos[word[1]]=word[0]只为每个键添加一个单词,但是如果我尝试像[].append(word[0])这样的操作,字典会将所有值返回为NONE。

您似乎在做大量的双重工作,但要解决您的特定问题:

for word in words_pos:
    tokens_pos[word[1]].append(word[0])
你应该做你想做的事

基本上,您正在覆盖具有相同键的现有值,因此最后只保留具有该键的最后写入值

tokens_pos[word[1]] = word[0]