开发者社区 问答 正文

Python如何使用机器学习从句子中找到每个单词的索引

这是我的句子-:

s1= "my name is Jouy" s2= "my name is 1010$H" 有执行此操作的库,例如textstat,word2vect

我想找到每个单词的索引

(HERE I CAN NOT DO SIMPLE OPERATION , I KNOW THAT WAY) 我不知道该怎么做

如果可能的话请建议我

谢谢

展开
收起
被纵养的懒猫 2019-09-30 14:56:31 467 分享 版权
阿里云 AI 助理回答

在Python中,如果你想要获取字符串中每个单词的索引,其实并不需要特定的库如textstat或word2vec,你可以直接使用Python的基本功能来实现。下面是一个简单的方法来获取每个单词的起始索引:

s1 = "my name is Jouy"
s2 = "my name is 1010$H"

def get_word_indices(sentence):
    indices = []
    start = 0
    for word in sentence.split():
        indices.append((word, start))
        # 更新起始位置到当前单词的末尾
        start += len(word) + 1  # +1 是为了考虑单词间的空格
    return indices

# 对两个句子应用函数
indices_s1 = get_word_indices(s1)
indices_s2 = get_word_indices(s2)

print("Indices for s1:", indices_s1)
print("Indices for s2:", indices_s2)

这段代码定义了一个get_word_indices函数,它接收一个字符串作为输入,然后遍历这个字符串(按空格分割成单词),为每个单词记录其在原字符串中的起始位置。注意,这里我们假设单词之间由单个空格分隔,并且没有处理前导或尾随空格的情况。

输出将会是包含每个单词及其起始索引的元组列表,如下所示:

Indices for s1: [('my', 0), ('name', 3), ('is', 8), ('Jouy', 11)]
Indices for s2: [('my', 0), ('name', 3), ('is', 8), ('1010$H', 11)]

这样,你就可以得到每个单词对应的起始索引了。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答