正在阅读文档(https://docs.python.org/2/tutorial/inputoutput.html):
For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code:
If you want to read all the lines of a file in a list you can also use
list(f)
orf.readlines()
.
所以我试了一下:
with open(file) as f:
dictionary = sorted(list(f))
#debug
print dictionary
结果是:
['anuria\n', 'anus\n', 'anuses\n', 'anvil\n', 'anvils\n', 'anxiety\n',
'anxious\n ', 'any\n', 'anybody\n', 'anyhow\n', 'anymore\n',
'anyone\n', 'anyplace\n', 'any thing\n', 'anytime\n', 'anyway\n',
'anywhere\n', 'anywise\n', 'aorta\n', 'aortae \n', 'aortal\n',
'aortas\n', 'aortic\n', 'aortitis\n', 'aoudad\n', 'aoudads\n',
'apace\n', 'apache\n', 'apaches\n', 'apanage\n', 'apart\n',
'apathies\n', 'apathy'...]
两个问题:
为什么\n
换行提要存在?
有办法把它去掉吗?或者我必须使用readline()
并手动追加?
之所以有换行符,是因为文件中的每一行都以它结尾。Python在读取数据时不会删除此字符。你知道吗
要删除换行符,可以使用generator expression并在每行上调用^{} :
另外,您的变量有点命名错误;
sorted
不返回字典,而是返回一个列表:您可以做的一些事情:可以使用strip删除换行符:
您可以使用切片,因为最后一个字符始终是换行符:
让lambda来做:
相关问题 更多 >
编程相关推荐