python - 您如何将文件读入字典,其键为单词长度,值作为具有该长度的单词
问题描述
对于我的代码,我需要读取一个文件并将其放入带有列表的字典中。例如,如果 file.txt 包含:
cat
dog
as
mars
hello
我需要将其格式化为{2 : ["as"], 3 : ["cat", "dog"], 4 : ["mars"], 5 : ["hello"]}
这是我迄今为止尝试过的
dictionary = {}
file = open(dictionary_file, "r")
for line in file:
x = line
b = len(line)-1
x = line[0:b]
dictionary[b].append(x)
解决方案
d = {}
with open('data.txt', 'r') as fp:
for line in fp.readlines():
line = line.strip()
if not line:
continue
key = len(line)
if not key in d:
d[key] = []
d[key].append(line)
print(sorted(d.items(), key=lambda item:item[0]))
推荐阅读
- html - JSF inserts
tag automatically, disturbing the order on page
- java - Spring,Spring-MVC:将 XML 配置迁移到 Java,导致找不到数据源错误
- react-native - 反应导航弹出到另一个堆栈中的屏幕
- lua - flashair w04 上的 lua lfs 似乎不起作用
- javascript - 在 React 类中缓存 DOM 值的好模式是什么
- scala - 在 Scala 中设置隐式函数返回
- python - Django信号发送两次
- python - 在 matplotlib.pyplot 中使用虚线标记 y 值
- java - 通过注解名称查找 pojo 字段
- sql - 存储过程在不同的服务器上给出不同的结果集