找回密码
 注册
搜索
[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
查看: 12638|回复: 1

[原创代码] Python提取一组数据的第一个字符以及第一个到第三个字符

[复制链接]
发表于 2015-12-19 06:06:25 | 显示全部楼层 |阅读模式
  1. """
  2. python正则提取一组数据的第一个字符以及第一个到第三个字符
  3. http://www.bathome.net/thread-38635-1-1.html
  4. 依山居 3:43 2015/12/19

  5. """
  6. import re
  7. with open("data.txt") as f:
  8.     txt=f.read()
  9.    
  10. rep=re.compile("(\w|~{1})(\w*)")
  11. result1=re.sub(rep,"\\1",txt)
  12. with open("result1.txt","w+") as f:
  13.     f.write(result1)

  14. rep=re.compile("(\w{3})(\w*)")
  15. result2=rep.sub("\\1",txt)
  16. with open("result2.txt","w+") as f:
  17.     f.write(result2)

  18.         
复制代码
发表于 2015-12-19 06:29:57 | 显示全部楼层
  1. """
  2. python切片提取一组数据的第一个字符以及第一个到第三个字符.py
  3. http://www.bathome.net/thread-38635-1-1.html
  4. 依山居 1:02 2015/12/17
  5. """
  6. with open("data.txt") as f:
  7.     txt=[r.rstrip().split() for r in f.readlines()]
  8.    
  9. result1=''
  10. result2=''
  11. for r in txt:
  12.     sstr1=''
  13.     sstr2=''
  14.     for s in r:
  15.         if len(s)>3:
  16.             sstr1+=s[0]+" "
  17.             sstr2+=s[0:3]+" "
  18.         else:
  19.             sstr1+=s
  20.             sstr2+=s
  21.     result1+=sstr1+"\n"
  22.     result2+=sstr2+"\n"

  23. with open("result1.txt","w+") as f:
  24.     f.write(result1)
  25. with open("result2.txt","w+") as f:
  26.     f.write(result2)
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|批处理之家 ( 渝ICP备10000708号 )

GMT+8, 2026-3-17 01:03 , Processed in 0.017099 second(s), 8 queries , File On.

Powered by Discuz! X3.5

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表