Board logo

标题: [问题求助] python这个代码如何写? [打印本页]

作者: netdzb    时间: 2020-5-4 00:32     标题: python这个代码如何写?

AB[rb][qb][pc][oc][nd][ne][nf][og][oh][qh][rg][sf][ri][se][sb]
AW[qg][pg][of][pe][pd][qc][rc][sc][re][rf]

要求得到这个结果
rb,qb,pc,oc,nd,ne,nf,og,oh,qh,rg,sf,ri,se,sb   // 打印第一行
qg,pg,of,pe,pd,qc,rc,sc,re,rf                  // 打印第二行


按照']['进行分割的话,前面后对不上啊?
作者: wujunkai    时间: 2020-5-4 06:46

回复 1# netdzb


    正则表达式
  1. re.split(text,r'[[]]')
复制代码

作者: netdzb    时间: 2020-5-4 07:51

回复 2# wujunkai


这个表达式是什么意思?
作者: sxw    时间: 2020-5-4 08:01

使用 Raku(之前叫 Perl 6):
  1. .comb(/ '[' <( \w+ )> ']' /).join(',').say for $=finish.lines;
  2. =finish
  3. AB[rb][qb][pc][oc][nd][ne][nf][og][oh][qh][rg][sf][ri][se][sb]
  4. AW[qg][pg][of][pe][pd][qc][rc][sc][re][rf]
复制代码

作者: netdzb    时间: 2020-5-4 08:17

回复 4# sxw

comb是一个模块吗?
代码能否解释一下,谢谢!
作者: netdzb    时间: 2020-5-4 08:20

回复 4# sxw


<( \w+ )> 这个表示什么意思?
作者: ivor    时间: 2020-5-4 08:21

python3.x
  1. import re
  2. str = """AB[rb][qb][pc][oc][nd][ne][nf][og][oh][qh][rg][sf][ri][se][sb]
  3. AW[qg][pg][of][pe][pd][qc][rc][sc][re][rf]"""
  4. for i in str.split('\n'):
  5.     s = re.findall("\[(.*?)\]", i)
  6.     print(','.join(s))
复制代码

作者: netdzb    时间: 2020-5-4 08:30

回复 7# ivor


[] 里面是a-s的小写字母,如果超越范围就报错退出。
该怎么改?
作者: ivor    时间: 2020-5-4 08:53

本帖最后由 ivor 于 2020-5-4 09:10 编辑
  1. import re
  2. str = """AB[rb][qb][pc][oc][nd][ne][nf][og][oh][qh][rg][sf][ri][se][sb]
  3. AW[qg][pg][of][pe][pd][qc][rc][sc][re][rf]"""
  4. for i in str.split('\n'):
  5.     if (re.search("\[[a-s]*[t-z]+[a-s]*\]",i)): #检测到t-z字母则抛出UserWarning异常
  6.         raise UserWarning
  7.     s = re.findall("\[([a-s]+)\]", i)
  8.     print(','.join(s))
复制代码

作者: sxw    时间: 2020-5-4 21:31

回复 5# netdzb


    comb 是一个函数, 接收一个正则表达式, 会过滤下来所有匹配的字符串
作者: sxw    时间: 2020-5-4 21:32

回复 6# netdzb


    <( 表示匹配的开始, )> 表示匹配的结束。合起来表示 ,只有在 <(  和  )> 之间的字符串才会保留下来。
作者: netdzb    时间: 2020-5-5 04:12

回复 11# sxw


   
\w+表示什么? 是表示小写字母w以后的字母吗?
作者: wujunkai    时间: 2020-5-5 12:18

回复 12# netdzb


    我还是建议你先系统地学完正则表达式,再来问
作者: netdzb    时间: 2020-5-5 13:20

回复 13# wujunkai

他贴的是perl关系的正则,和python的规则不一样。
作者: wujunkai    时间: 2020-5-5 21:55

本帖最后由 wujunkai 于 2020-5-5 22:25 编辑

回复 14# netdzb


    可能在操作细节上会有出入,但\w和+的含义应该是不会变的
https://www.cnblogs.com/tina-python/p/5508402.html
作者: Gin_Q    时间: 2020-5-10 15:29

开始学Python了!
  1. >>> import re
  2. >>> a
  3. 'AB[rb][qb][pc][oc][nd][ne][nf][og][oh][qh][rg][sf][ri][se][sb]'
  4. >>> b=re.findall('[a-z]{2}',a)
  5. >>> b
  6. ['rb', 'qb', 'pc', 'oc', 'nd', 'ne', 'nf', 'og', 'oh', 'qh', 'rg', 'sf', 'ri', 'se', 'sb']
  7. >>> ''.join(b)
  8. 'rbqbpcocndnenfogohqhrgsfrisesb'
  9. >>>
复制代码





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