正在阅读文档(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并调用str.rstrip在每一行:
with open(file) as f:
dictionary = sorted(line.rstrip() for line in f)
此外,您的变量命名有些错误; sorted 返回的不是字典而是列表:
>>> sorted(i for i in xrange(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
