我需要这组代码能够将句子/句子2/句子3转换为三个位置,作为每个句子的单独列表,最好使用与我尝试过的方法类似的方法。所以输出应该是这样的:
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
sentence = ("ask not what you can do for your country ask what your country can do for you")
sentence2 = ("some people enjoy computing others do not enjoy computing")
sentence3 = ("i will use this as my last sentence as i do not need another sentence")
d = {}
i = 0
values = []
for i, word in enumerate(sentence, sentence2, sentence3(" ")):
if not word in d:
d[word] = (i + 1)
values += [d[word]]
print(values)
发布于 2016-01-11 05:22:48
这就解决了这个问题
def conv2pos(*sentences):
def conv_one(s):
words = s.split()
word_pos = {w:words.index(w) for w in set(words)}
return [word_pos[w]+1 for w in words]
return [conv_one(s) for s in sentences]
print(conv2pos(sentence, sentence2, sentence3))
对于给定的句子,它会产生
[
[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 conv2pos(*sentences):
def conv_one(s):
words = s.split()
return [words.index(w)+1 for w in words]
return [conv_one(s) for s in sentences]
https://stackoverflow.com/questions/34710342
复制相似问题