Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 检测两行括号中的内容_Python_Python 2.7 - Fatal编程技术网

Python 检测两行括号中的内容

Python 检测两行括号中的内容,python,python-2.7,Python,Python 2.7,如果我有这样的文字 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&g

如果我有这样的文字

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>
1
他是个[男人]
吕èun[uomo]
2.
她是[女人]
莱昂娜·唐娜
3.
他工作很好
路易·拉沃拉[bene]
我只想在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])
line=str()
num=str()
line1=str()
num1=str()
对于i,枚举(文件)中的行:
lines=iter(文件1)
如果第.startswith(“”)行:
行+='%s\n'%line.strip()
num+='%s\n'%filer1[i-1]
如果第.startswith(“”)行:
line1+='%s\n'%line.strip()
num1+='%s\n'%filer1[i-2]
对于直线中的l.splitlines():
对于第1行中的ll。拆分行():
对于数量为n的拆分行():
对于num1.splitlines()中的nn:
如果n==nn:
m=re.findall(r“\[(.*?\]),l)
mm=re.findall(r“\[(.*?\]),ll)
如果m和mm:
打印'[{}]'。格式(m[0]),'[{}]'。格式(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())

假设您的文件严格遵循三行模式,您可以

# assumes Python 2.7
from itertools import izip_longest
import re

INPUT = "translations.txt"

# from itertools documentation
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

in_brackets = re.compile("\[(.*?)\]").search

def main():
    with open(INPUT) as inf:
        for num,en,it in grouper(inf, 3, ""):
            en = in_brackets(en)
            it = in_brackets(it)
            if en and it:
                print("[{}] -> [{}]".format(en.group(1), it.group(1)))

main()

您希望所有字符串都放在方括号内的任何位置,还是只希望尖括号标记中的字符串放在方括号内?此外,您应该在遇到问题时来这里,而不是在开始之前(您没有代码;您只是要求我们为您完成)。请研究如何使用python的正则表达式模块(
import re
)。自从发布代码后,删除了下一票。
# assumes Python 2.7
from itertools import izip_longest
import re

INPUT = "translations.txt"

# from itertools documentation
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

in_brackets = re.compile("\[(.*?)\]").search

def main():
    with open(INPUT) as inf:
        for num,en,it in grouper(inf, 3, ""):
            en = in_brackets(en)
            it = in_brackets(it)
            if en and it:
                print("[{}] -> [{}]".format(en.group(1), it.group(1)))

main()