【发布时间】:2021-11-29 20:39:38
【问题描述】:
给定一个列表 [[["source1"], ["target1"], ["alignment1"]], ["source2"], ["target2"], ["alignment2"]], ...] ,我想提取源中与目标中的单词对齐的单词。
例如,在英德句子对 The hat is on the table 中。 - Der Hut liegt auf dem Tisch .,我想打印以下内容:
The - Der
hat - Hut
is - liegt
on - auf
the - dem
table - Tisch
. - .
所以我写了以下内容:
en_de = [
[['The', 'hat', 'is', 'on', 'the', 'table', '.'], ['Der', 'Hut', 'liegt', 'auf', 'dem', 'Tisch', '.'], '0-0 1-1 2-2 3-3 4-4 5-5 6-6'],
[['The', 'picture', 'is', 'on', 'the', 'wall', '.'], ['Das', 'Bild', 'hängt', 'an', 'der', 'Wand', '.'], '0-0 1-1 2-2 3-3 4-4 5-5 6-6'],
[['The', 'bottle', 'is', 'under', 'the', 'sink', '.'], ['Die', 'Flasche', 'ist', 'under', 'dem', 'Waschbecken', '.'], '0-0 1-1 2-2 3-3 4-4 5-5 6-6']
]
for group in en_de:
src_sent = group[0]
tgt_sent = group[1]
aligns = group[2]
split_aligns = aligns.split()
hyphen_split = [align.split("-") for align in split_aligns]
align_index = hyphen_split[0]
print(src_sent[int(align_index[0])],"-", tgt_sent[int(align_index[1])])
这将按预期打印src_sent 和tgt_sent 的索引位置0 中的单词:
The - Der
The - Das
The - Die
现在,我不知道如何打印src_sent 和tgt_sent 的所有索引位置的单词。显然,我可以手动将align_index 更新为句子对中每个位置的新索引位置,但在完整数据集上,某些句子将有多达 25 个索引位置。
有没有办法通过每个索引位置进行循环?
当我尝试时:
align_index = hyphen_split[0:]
print(src_sent[int(align_index[0])],"-", tgt_sent[int(align_index[1])])
我收到了TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
很明显align_index 不能是一个列表,但我不知道如何将它转换成可以做我想做的事情。
任何建议或帮助将不胜感激。提前谢谢你。
【问题讨论】:
-
您提供的所有示例仅包含 1-1 比对。如果这是自然语言数据,您应该处理更复杂的对齐方式。您是只对这种线性情况感兴趣,还是对更一般的字对齐情况感兴趣?
-
在线
align_index = hyphen_split[0:],您实际上是在设置align_index = [(0,0),(1,1),...]。那是你的意思吗?还是您的意思是align_index = hyphen_split[0]?目前尚不清楚这行代码试图完成什么。 -
我想我刚刚弄明白了——你需要的是
for align_index in hyphen_split:,然后是你的打印语句,缩进更深一层。 -
@joanis - 是的,没错。示例不是很复杂,只有 1-1 对齐。我正在使用的完整数据集是 NL 数据,因此具有一对多、多对一的对齐方式。那是我将来要跨过的一座桥。是的,你准确地发现了我的问题。谢谢。
标签: python for-loop nlp linguistics