识别句子中的单词,将这些单词存储在列表中并用该单词在列表中的位置替换每个单词的程序 [英] Program that identifies words in a sentence, stores these in a list and replaces each word with the position of that word in the list

查看:34
本文介绍了识别句子中的单词,将这些单词存储在列表中并用该单词在列表中的位置替换每个单词的程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个表单可视化基本程序,可以输出一个单词在句子中的位置,有没有办法可以只用数字输出整个句子,例如:猫与另一只猫战斗将是 1,2,3、4、1、6、7.

I have created a form visual basic program that ouputs the position of a word in a sentence, is there a way that i could output the whole sentence with only numbers for example: The cat fought another cat would be 1,2,3,4,1,6,7.

非常感谢您的帮助.

推荐答案

您需要做的就是获取句子中不同单词的列表,然后遍历句子中的每个单词并用单词的索引替换单词作为输出.以下是如何完成此操作的示例:

All you need to do is get a list of the distinct words in the sentence, then iterate through each word of the sentence and substitute the word's index for the word as an output. Here's an example of how to accomplish that:

    Dim UserInput1 As String = "The cat fought another cat would be"
    Dim words As New List(Of String)

    'Here, we just add get a list of the distinct words in the sentence
    For Each Word As String In UserInput1.ToLower.Split(CChar(" "))
        If Not words.Contains(Word) Then words.Add(Word)
    Next

    'Looping through the words and their indexes
    'to show their relation just for this example
    For i As Integer = 0 To Words.Count - 1
        Debug.Print((i + 1).ToString & " = " & Words(i))
    Next
    'Outputs:
    '1 = the
    '2 = cat
    '3 = fought
    '4 = another
    '5 = would
    '6 = be


    'So now that we have our number/word relations,
    'we can just loop through the words and get the
    'output that you wanted, an index substitution of each word
    Dim output As String = Nothing
    For Each Word As String In UserInput1.ToLower.Split(CChar(" "))
        output &= (words.IndexOf(Word) + 1).ToString & ", "
    Next
    output = output.Substring(0, output.Length - 2)
    'output = "1, 2, 3, 4, 2, 5, 6"

这篇关于识别句子中的单词,将这些单词存储在列表中并用该单词在列表中的位置替换每个单词的程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆