如何创建字典,给出单词在fi中的位置

2024-05-19 00:44:46 发布

您现在位置:Python中文网/ 问答频道 /正文

code of what i have right now

我需要编写一个代码,读取一个字符串文件,然后返回一个字典,关键字是单词,值是单词在文件中出现的索引。 例如,如果字符串是“I want a cookie and a soda”,则字典将是

`{"I":[0], "want":[1] "a":[2,5], "cookie":[3], "and":[4], "soda":[6]}.`

Tags: and文件of字符串代码right字典cookie
2条回答
d = {}

with open("TempFile.txt") as f:
    for i, word in enumerate(f.read().split()):
        d[word] = d.get(word, []) + [i]

输出

{'I': [0], 'want': [1], 'a': [2, 5], 'cookie': [3], 'and': [4], 'soda': [6]}

使用enumerate来保持索引的运行比每次迭代调用list.index()更有效

test.txt的内容:这是一个cookie

with open("test.txt", "r") as file:
    contents = file.read()
    contents = contents.split(" ") #split string into a list

    count = 0

    dict = {}

    for word in contents:
        dict[word] = count
        count += 1
    print(dict)

相关问题 更多 >

    热门问题