gpt4 book ai didi

python - 如何在一个正则表达式中捕获所有正则表达式组?

转载 作者:太空狗 更新时间:2023-10-30 01:50:35 24 4
gpt4 key购买 nike

给定这样一个文件:

# For more information about CC-CEDICT see:
# http://cc-cedict.org/wiki/
A A [A] /(slang) (Tw) to steal/
AA制 AA制 [A A zhi4] /to split the bill/to go Dutch/
AB制 AB制 [A B zhi4] /to split the bill (where the male counterpart foots the larger portion of the sum)/(theater) a system where two actors take turns in acting the main role, with one actor replacing the other if either is unavailable/
A咖 A咖 [A ka1] /class "A"/top grade/
A圈兒 A圈儿 [A quan1 r5] /at symbol, @/
A片 A片 [A pian4] /adult movie/pornography/

我想构建一个 json 对象:

  • 跳过以#开头的行
  • 将行分成 4 部分
    1. 繁体字(从开始^到下一个空格)
    2. 简化字符(从第一个空格跨越到第二个空格)
    3. 拼音(跨越方括号 [...])
    4. 第一个 / 到最后一个 / 之间的注释空间(请注意,在某些情况下注释中可以有斜线,例如 /adult movie/色情/

我目前是这样做的:

>>> for line in text.split('\n'):
... if line.startswith('#'): continue;
... line = line.strip()
... simple, _, line = line.partition(' ')
... trad, _, line = line.partition(' ')
... print simple, trad
...
A A
AA制 AA制
AB制 AB制
A咖 A咖
A圈兒 A圈儿
A片 A片

要获得 [...],我必须这样做:

>>> import re
>>> line = "A片 A片 [A pian4] /adult movie/pornography/"
>>> simple, _, line = line.partition(' ')
>>> trad, _, line = line.partition(' ')
>>> re.findall(r'\[.*\]', line)[0].strip('[]')
'A pian4'

要找到 /.../,我必须这样做:

>>> line = "A片 A片 [A pian4] /adult movie/pornography/"
>>> re.findall(r'\/.*\/$', line)[0].strip('/')
'adult movie/pornography'

我如何使用正则表达式组一次捕获所有这些进行多个分区/拆分/查找?

最佳答案

我可以使用正则表达式提取信息。这样,您可以分组捕获 block ,然后根据需要处理它们:

import re

with open("myfile") as f:
data = f.read().split('\n')
for line in data:
if line.startswith('#'): continue
m = re.search(r"^([^ ]*) ([^ ]*) \[([^]]*)\] \/(.*)\/$", line)
if m:
print(m.groups())

即正则表达式将字符串分成以下几组:

^([^ ]*) ([^ ]*) \[([^]]*)\] \/(.*)\/$
^^^^^ ^^^^^ ^^^^^ ^^
1) 2) 3) 4)

即:

  1. 第一个词。

  2. 第二个字。

  3. [] 中的文本。

  4. / 到行尾之前的 / 的文本。

它返回:

('A', 'A', 'A', '(slang) (Tw) to steal')
('AA制', 'AA制', 'A A zhi4', 'to split the bill/to go Dutch')
('AB制', 'AB制', 'A B zhi4', 'to split the bill (where the male counterpart foots the larger portion of the sum)/(theater) a system where two actors take turns in acting the main role, with one actor replacing the other if either is unavailable')
('A咖', 'A咖', 'A ka1', 'class "A"/top grade')
('A圈兒', 'A圈儿', 'A quan1 r5', 'at symbol, @')
('A片', 'A片', 'A pian4', 'adult movie/pornography')

关于python - 如何在一个正则表达式中捕获所有正则表达式组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36686732/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com