[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

[技术讨论] 一行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'))
复制代码

测试删除掉.strip()之后得出的结果为12,但len实际为11,添加.strip()之后结果是正确的。查了一下.strip()为删除空白符,这里的空白符也包括换行符吗
踏实一些点.不要着急.你想要的时间都会给你.2

TOP

回复 2# 慕夜蓝化

包括

TOP

回复 3# pcl_test


    嗯嗯!
踏实一些点.不要着急.你想要的时间都会给你.2

TOP

f.close()
应该是可以省掉的。
去学去写去用才有进步。安装python3代码存为xx.py 双击运行或右键用IDLE打开按F5运行

TOP

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

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

rstrip('\n') 这样应该更靠谱。只清除掉\n
去学去写去用才有进步。安装python3代码存为xx.py 双击运行或右键用IDLE打开按F5运行

TOP

返回列表