如何提取匹配的字符串到defaultdict(集)?Python



我有一个文本文件,其中有这样几行(见下文),其中一个英语句子后面跟着一个西班牙语句子和由" {##} "分隔的等效翻译表。(如果你知道它是giza-pp的输出)

你要求在下一个课程中就这个问题进行辩论几天,在这部分会议期间。{##} SUS señorías han solicitado联合国辩论严肃地讨论问题próximos días,甚至讨论问题Período de sesiones。{##} 0-0 0-1 1-2 - 2-3 - 4-5 - 6-7 - 7-8 -912-10 13-11 14-11 15-12 16-13 17-14 9-15 10-16 11-17 18-18 17-19 19-21-

翻译表可以这样理解,0-0 0-1表示英语中的第0个单词(即you)匹配西班牙语中的第0和第1个单词(即sus señorías)

假设我想知道course在西班牙语中的翻译是什么,通常我会这样做:

from collections import defaultdict
eng, spa, trans =  x.split(" {##} ")
tt = defaultdict(set)
for s,t in [i.split("-") for i in trans.split(" ")]:
  tt[s].add(t)
query = 'course'
for i in spa.split(" ")[tt[eng.index(query)]]:
  print i

是否有一个简单的方法来做上面的?regex可以吗?line.find() ?

经过一些尝试后,我不得不这样做,以覆盖许多其他问题,如MWE和丢失的翻译:

def getTranslation(gizaline,query):
    src, trg, trans =  gizaline.split(" {##} ")
    tt = defaultdict(set)
    for s,t in [i.split("-") for i in trans.split(" ")]:
        tt[int(s)].add(int(t))
    try:
        query_translated =[trg.split(" ")[i] for i in tt[src.split(" ").index(query)]]
    except ValueError:
        for i in src.split(" "):
            if "-"+query or query+"-" in i:
                query = i
                break
        query_translated =[trg.split(" ")[i] for i in tt[src.split(" ").index(query)]]
    if len(query_translated) > 0:
        return ":".join(query_translated)
    else:
        return "#NULL"

这种方式很好,但我会稍微不同,使用list而不是set,以便我们可以正确排序单词(set将按字母顺序输出单词,不完全是我们想要的):

文件:q_15125575.py

#-*- encoding: utf8 -*-
from collections import defaultdict
INPUT = """you have requested a debate on this subject in the course of the next few days , during this part-session . {##} sus señorías han solicitado un debate sobre el tema para los próximos días , en el curso de este período de sesiones . {##} 0-0 0-1 1-2 2-3 3-4 4-5 5-6 6-7 7-8 8-9 12-10 13-11 14-11 15-12 16-13 17-14 9-15 10-16 11-17 18-18 17-19 19-21 20-22"""
if __name__ == "__main__":
    english, spanish, trans = INPUT.split(" {##} ")
    eng_words = english.split(' ')
    spa_words = spanish.split(' ')
    transtable = defaultdict(list)
    for e, s in [i.split('-') for i in trans.split(' ')]:
        transtable[eng_words[int(e)]].append(spa_words[int(s)])
    print(transtable['course'])
    print(transtable['you'])
    print(" ".join(transtable['course']))
    print(" ".join(transtable['you']))
输出:


[' curso ']
("苏氏",se xc3 xb1or xc3 xadas ']
curso
sus体现

代码略长,因为我使用的是实际的单词而不是索引-但这允许您直接从transtable

查找

然而,你的方法和我的方法都失败在同一个问题上:重复单词。
print(" ".join(transtable['this'])
给:
el este
它至少是按单词出现的顺序排列的,所以它是可行的。想要翻译'this'的第一次出现?
transtable['this'][0]会给你第一个单词。

和使用你的代码:

tt = defaultdict(set)
for e, s in [i.split('-') for i in trans.split(' ')]:
    tt[int(e)].add(int(s))
query = 'this'
for i in tt[eng_words.index(query)]:
    print i

给了:
7

你的代码将只打印一个单词第一个出现的索引