【问题标题】:list(file) appends \n to each linelist(file) 将 \n 附加到每一行
【发布时间】:2014-11-28 02:27:10
【问题描述】:

正在阅读文档 (https://docs.python.org/2/tutorial/inputoutput.html):

为了从文件中读取行,您可以遍历文件对象。这是内存效率高、速度快并且代码简单:

如果您想读取列表中文件的所有行,也可以使用list(f)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() 并手动附加?

【问题讨论】:

  • 请注意最后一个条目缺少换行符 - 显然 list() 为您提供文件的内容并且文件包含换行符(如果您在记事本样式的应用程序中打开它,您将看到换行符)跨度>
  • 我从控制台复制粘贴,所以我可能截断了“最后一个条目”(大约有 50k 字或更多 - 直到完成才让它运行)
  • 很公平,但重点仍然存在 - list() 方法为您提供文件的内容 - 它不是“添加”任何内容。
  • @MattCoubrough 我知道你来自哪里。可能我应该说“为什么不去掉 \n”而不是问它为什么在那里。谢谢

标签: python list file python-2.7


【解决方案1】:

有换行符是因为文件中的每一行都以它结尾。 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]
>>>

【讨论】:

  • 执行此操作时的约定是什么:line.rstrip() for line in f 是的,您说得对,它实际上是一个列表,但只是为了说明我正在阅读字典中的单词跨度>
  • line.rstrip() for line in f 是一个生成器表达式。我包含了文档的链接。基本上,它与列表推导 [line.rstrip() for line in f] 相同,只是它懒惰地生成项目(一个接一个而不是一次全部生成)。这样可以节省内存,因为它避免了创建不必要的列表。
  • 很难理解这个概念,但我会尝试阅读更多内容。谢谢。
【解决方案2】:

您可以做的一些事情:您可以使用 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

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 2014-04-03
    • 2017-08-26
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    相关资源
    最近更新 更多