2024-05-19 00:44:46 发布
网友
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]}.`
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()更有效
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)
输出
{'I': [0], 'want': [1], 'a': [2, 5], 'cookie': [3], 'and': [4], 'soda': [6]}
使用enumerate来保持索引的运行比每次迭代调用
list.index()
更有效test.txt的内容:这是一个cookie
相关问题 更多 >
编程相关推荐