Chinaunix

标题: 求教python文本处理 [打印本页]

作者: sullybear    时间: 2014-03-16 00:21
标题: 求教python文本处理
已知文件
A   1    3
A   4    5
B   2    3
B   4    6
B   8    9


得出
A  1    5
B   2    6
B   8    9
的脚本

文件行数会比较多,将数字连续的整合
作者: timespace    时间: 2014-03-16 11:50
清楚的解释下规则,别人不一定看懂你的例子。
作者: sullybear    时间: 2014-03-16 22:03
对于相同的元素A,如果第二行的第一个数字是第一行的第二个数字的值+1,即可以实现连续
作者: ssfjhh    时间: 2014-03-17 09:28
回复 3# sullybear


    还是没看懂呀。
作者: timespace    时间: 2014-03-17 11:06
回复 3# sullybear
但愿我看明白了。generator实现,不管文件有多大,占用很少内存。
  1. import io

  2. infile = io.StringIO(
  3. '''A   1    3
  4. A   4    5
  5. B   2    3
  6. B   4    6
  7. B   8    9
  8. ''')

  9. def parse(fp):
  10.     for line in fp:
  11.         fields = line.split()
  12.         if len(fields) == 3 and fields[1].isdigit() and fields[2].isdigit():
  13.             fields[1], fields[2] = int(fields[1]), int(fields[2])
  14.             yield fields

  15. def merge(records):
  16.     value = next(records, None)
  17.     if value is None:
  18.         return

  19.     for e in records:
  20.         if value[0] == e[0] and value[2] + 1 == e[1]:
  21.             value[2] = e[2]
  22.         else:
  23.             yield value
  24.             value = e
  25.     yield value

  26. def main():
  27.     for e in merge(parse(infile)):
  28.         print(*e)

  29. if __name__ == '__main__':
  30.     main()
复制代码
保存为main.py,执行:
  1. bash-3.2 $python --version
  2. Python 3.3.4
  3. bash-3.2 $python main.py
  4. A 1 5
  5. B 2 6
  6. B 8 9
复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2