gpt4 book ai didi

python - 检测两行括号中的内容

转载 作者:太空宇宙 更新时间:2023-11-03 18:25:00 27 4
gpt4 key购买 nike

如果我有这样的文字

1
<src> he is a [man]</src>
<tgt>lui è un [uomo]</tgt>
2
<src> she is a [woman]</src>
<tgt>lei è una donna</tgt>
3
<src> he works well</src>
<tgt> lui lavora [bene]</tgt>

并且我想仅当括号出现在 src 和 tgt 行中时才检测括号之间的字符串,因此在上面的文本中,我只想检测 [man][uomo],因为在 src 行中是 [man],tgt 行中有 [uomo]。有人可以帮我吗

我尝试了这段代码

line = str()
num = str()
line1 = str()
num1 = str()

for i, line in enumerate(file):
lines = iter(filer1)
if line.startswith("<src>"):
line += '%s\n' % line.strip()
num += '%s\n' % filer1[i-1]
if line.startswith("<tgt>"):
line1 += '%s\n' % line.strip()
num1 += '%s\n' % filer1[i-2]
for l in line.splitlines():
for ll in line1.splitlines():
for n in num.splitlines():
for nn in num1.splitlines():
if n ==nn:
m = re.findall(r"\[(.*?)\]",l)
mm = re.findall(r"\[(.*?)\]",ll)
if m and mm:
print '[{}]'.format(m[0]), '[{}]'.format(mm[0])

最佳答案

基本上,您应该做的是:首先,清理您的文本输入,以便您拥有一个列表列表,其中每个子列表包含一个 src 行和一个 tgt 行。然后,循环遍历各行,并使用 re 测试 src 和 tgt 中方括号内是否存在文本。如果src和tgt都有括号文本,则显示它们;否则,不要。

这应该非常简单,如下所示:

import re

# see <http://stackoverflow.com/a/312464/1535629>
def chunks(l, n):
for i in xrange(0, len(l), n):
yield l[i:i+n]

text = '''1
<src> he is a [man]</src>
<tgt>lui è un [uomo]</tgt>
2
<src> she is a [woman]</src>
<tgt>lei è una donna</tgt>
3
<src> he works well</src>
<tgt> lui lavora [bene]</tgt>'''
lines = text.split('\n')
linepairs = [chunk[1:] for chunk in chunks(lines, 3)]

regex = re.compile(r'\[\w*\]')
for src, tgt in linepairs:
src_match = re.search(regex, src)
tgt_match = re.search(regex, tgt)
if src_match and tgt_match:
print(src_match.group(), tgt_match.group())

结果:

[man] [uomo]

关于python - 检测两行括号中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23376169/

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