Board logo

标题: [技术讨论] 一行Python代码获取文件最长的行的长度 [打印本页]

作者: Python    时间: 2012-3-22 11:25     标题: 一行Python代码获取文件最长的行的长度

#普通写法是逐行读取文件内容,用“擂台赛”的方法获取最长的行:
  1. f = open('a.txt', 'r')
  2. longest = 0
  3. while True:
  4.     linelen = len(f.readline().strip())
  5.     if not linelen:
  6.         break
  7.     if linelen > longest:
  8.         longest = linelen
  9. f.close()
  10. print longest
复制代码
#考虑到尽早释放文件句柄,应该把关闭文件的操作提到前面:
  1. f = open('a.txt', 'r')
  2. longest = 0
  3. allLines = f.readlines()
  4. f.close()
  5. for line in allLines:
  6.     linelen = len(line.strip())
  7.     if linelen > longest:
  8.         longest = linelen
  9. print longest
复制代码
#使用列表解析在读取文件的时候就进行strip()处理
  1. f = open('a.txt', 'r')
  2. longest = 0
  3. allLines = [x.strip() for x in f.readlines()]
  4. f.close()
  5. for line in allLines:
  6.     linelen = len(line)
  7.     if linelen > longest:
  8.         longest = linelen
  9. print longest
复制代码
#使用迭代器获取长度的集合,避免readlines()读取所有行:
  1. f = open('a.txt', 'r')
  2. allLineLens = [len(x.strip()) for x in f]
  3. f.close()
  4. print max(allLineLens)
复制代码
#用生成器表达式代替列表解析
  1. f = open('a.txt', 'r')
  2. longest = max(len(x.strip()) for x in f)
  3. f.close()
  4. print longest
复制代码
#去掉文件打开模式(默认为读取):
  1. print max(len(x.strip()) for x in open('a.txt'))
复制代码

作者: 慕夜蓝化    时间: 2016-1-13 15:42

测试删除掉.strip()之后得出的结果为12,但len实际为11,添加.strip()之后结果是正确的。查了一下.strip()为删除空白符,这里的空白符也包括换行符吗
作者: pcl_test    时间: 2016-1-13 16:14

回复 2# 慕夜蓝化

包括
作者: 慕夜蓝化    时间: 2016-1-13 19:34

回复 3# pcl_test


    嗯嗯!
作者: codegay    时间: 2016-1-14 01:18

f.close()
应该是可以省掉的。
作者: codegay    时间: 2016-2-2 07:56

>>> s=" s s "
>>> s.strip()
's s'

直接strip()的话,会把字符串两端的空白字符也清除掉。
>>> " s  s s \n".rstrip('\n')
' s  s s '

rstrip('\n') 这样应该更靠谱。只清除掉\n




欢迎光临 批处理之家 (http://www.bathome.net/) Powered by Discuz! 7.2