如何将匹配的字符串提取到defaultdict(set)中?Python
我有一个文本文件,里面的内容是这样的(见下文):一行英文句子后面跟着一个西班牙文句子,还有一个用"{##}
"分隔的翻译表。(如果你知道的话,这就是giza-pp
的输出)
你在接下来的几天里请求就这个主题进行辩论,在这个会议期间。{##} 尊敬的议员们请求在接下来的几天里就这个主题进行辩论,在这个会议期间。{##} 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
翻译表的意思是,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"
1 个回答
这样做是可以的,但我会稍微改一下,使用 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']
['sus', 'se\xc3\xb1or\xc3\xadas']
curso
sus señorías
这段代码稍微长一点,因为我使用的是实际的单词而不是索引 - 但这样可以让你直接从 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
你的代码只会打印出单词第一次出现的索引。