将位置列表转换为单词列表

时间:2016-01-11 17:48:56

标签: python-3.x

我有一段代码从多个单词列表中创建了一个位置列表,其中一个例子是:
不要问你能为国家做些什么,问你的国家能为你做些什么

有些人喜欢计算别人不喜欢的计算

我会用这个作为我的最后一句,因为我不需要另一句话

有以下职位列表:

[1,2,3,4,5,6,7,8,9,1,3,8,9,5,6,7,4],[1,2,3,4,5] 6,7,3,4],[1,2,3,4,5,6,7,8,5,1,11,12,13,14,8]

我现在需要创建一段可以做相反的代码: 从位置列表中重新创建句子

我坚持如何尝试这一点,并希望得到任何帮助。

如果不清楚请说出来我可以对我的措辞做出任何修改

2 个答案:

答案 0 :(得分:0)

In [22]: sentence = "some people enjoy computing others do not enjoy computing".split()

In [23]: poslist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 8, 9, 5, 6, 7, 4]

In [24]: ' '.join(sentence[i-1] for i in poslist)
Out[24]: 'some people enjoy computing others do not enjoy computing some enjoy enjoy computing others do not computing'

答案 1 :(得分:0)

data = ["ask not what you can do for your country ask what your country can do for you",
"some people enjoy computing others do not enjoy computing",
"i will use this as my last sentence as i do not need another sentence"]

pos_lists = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 8, 9, 5, 6, 7, 4], [1, 2, 3, 4, 5, 6, 7, 3, 4], [1, 2, 3, 4, 5, 6, 7, 8, 5, 1, 11, 12, 13, 14, 8]]

def regenerate_text(position_list, index):
    sentence = []
    for position in position_list:
        sentence.append(index[position])
    return " ".join(sentence)

for sentence, pos_list in zip(data, pos_lists):
    sentence_tokens = sentence.split()
    index = dict()
    for pos, word in enumerate(sentence_tokens):
        if word not in index:
            index.update({pos+1: word})
    new_sentence = regenerate_text(pos_list, index)
    assert(sentence == new_sentence)

您可以在句子中创建位置字典和相应的标记,然后使用字典获取标记的最终列表。 regenerate_text转换位置列表和字典以创建句子。