Python 如何将中的句子转换为向量

Python 如何将中的句子转换为向量,python,Python,我有一本字典,其中键是单词,值是这些单词的向量。 我有一个要转换成数组的句子列表。我得到了一个所有单词的数组,但我想有一个带有单词向量的句子数组,这样我就可以把它输入到神经网络中 sentences=["For last 8 years life, Galileo house arrest espousing man's theory", 'No. 2: 1912 Olympian; football star Carlisle Indian School; 6 MLB s

我有一本字典,其中键是单词,值是这些单词的向量。 我有一个要转换成数组的句子列表。我得到了一个所有单词的数组,但我想有一个带有单词向量的句子数组,这样我就可以把它输入到神经网络中

sentences=["For last 8 years life, Galileo house arrest espousing man's theory",
           'No. 2: 1912 Olympian; football star Carlisle Indian School; 6 MLB seasons Reds, Giants & Braves',
           'The city Yuma state record average 4,055 hours sunshine year'.......]    

word_vec={'For': [0.27452874183654785, 0.8040047883987427],
         'last': [-0.6316165924072266, -0.2768899202346802],
         'years': [-0.2496756911277771, 1.243837594985962],
         'life,': [-0.9836481809616089, -0.9561406373977661].....}   
我想把上面的句子转换成字典中相应单词的向量。

试试这个:

def sentence_to_list(sentence, words_dict):
    return [w for w in sentence.split() if w in words_dict]
因此,示例中的第一个句子将转换为:

['For', 'last', 'years', 'life']  # words not in the dictionary are not present here
更新

我想你需要删除标点符号。有几种方法可以使用多个分隔符拆分字符串,请检查以下答案:

尝试以下方法:

def sentence_to_list(sentence, words_dict):
    return [w for w in sentence.split() if w in words_dict]
因此,示例中的第一个句子将转换为:

['For', 'last', 'years', 'life']  # words not in the dictionary are not present here
更新


我想你需要删除标点符号。有几种方法可以使用多个分隔符来拆分字符串,请检查以下答案:

这将创建
向量
,包含向量列表(每句话一个列表):

如果要使用注释(,:等),请使用
re.findall
(导入注释)而不是
.split

words = re.findall(r"[\w']+", sentence)
sentence_vec = [ word_vec[word] for word in words if word in word_vec ]
如果不想跳过
word\u vec
中不可用的单词,请使用:

sentence_vec = [ word_vec[word] if word in word_vec else [0,0] for word in words ]

它将为每个缺少的单词放置
0,0

这将创建
向量
,包含向量列表(每句一个列表):

如果要使用注释(,:等),请使用
re.findall
(导入注释)而不是
.split

words = re.findall(r"[\w']+", sentence)
sentence_vec = [ word_vec[word] for word in words if word in word_vec ]
如果不想跳过
word\u vec
中不可用的单词,请使用:

sentence_vec = [ word_vec[word] if word in word_vec else [0,0] for word in words ]

它将为每个缺少的单词放置
0,0

您是否可以编辑此问题,以包括适当的预期输出(您说您想要一个包含单词向量的句子数组,但不清楚您的意思)以及您根据此处的指导原则迄今为止尝试的内容:。您是否可以编辑此问题以包括适当的预期输出(你说你想要一个带有单词向量的句子数组,但不清楚你的意思)以及根据这里的指导原则,到目前为止你已经尝试过的内容:。