识别句子中单词的程序,将它们存储在列表中,并用列表中该单词的位置替换每个单词

时间:2016-10-12 13:53:42

标签: vb.net visual-studio visual-studio-2010

我创建了一个表单视觉基本程序,它输出一个单词在句子中的位置,是否有一种方法可以输出整个句子只有数字例如:猫打另一只猫将是1,2, 3,4,1,6,7。

非常感谢您的所有帮助。

1 个答案:

答案 0 :(得分:1)

您需要做的就是获取句子中不同单词的列表,然后遍历句子中的每个单词,并将单词的索引替换为单词作为输出。以下是如何实现这一目标的示例:

    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"