列表(文件)将\n附加到每个lin

2024-03-29 09:19:30 发布

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

正在阅读文档(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) or f.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'...]

两个问题:

  1. 为什么\n换行提要存在?

  2. 有办法把它去掉吗?或者我必须使用readline()并手动追加?


Tags: theto文档httpsorgyoudocsdictionary
2条回答

之所以有换行符,是因为文件中的每一行都以它结尾。Python在读取数据时不会删除此字符。你知道吗

要删除换行符,可以使用generator expression并在每行上调用^{}

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]
>>>

您可以做的一些事情:可以使用strip删除换行符:

with open(file) as f:
    dictionary = sorted(map(str.strip,list(f)))
    #debug
print dictionary

您可以使用切片,因为最后一个字符始终是换行符:

dictionary = []
with open(file) as f:
    for x in f:
        dictionary.append(x[:-1])   # it will append everything except last character that is newline
    #debug
print sorted(dictionary)

让lambda来做:

with open(file) as f:
    dictionary = sorted(map(lambda x:x[:-1],f))
    #debug
print dictionary

相关问题 更多 >