我正在尝试创建一个程序,将对话并将其分为发言人,然后计算他们在整个对话中说了多少个单词。
考虑以下示例;
GEORGE
今天我们将讨论这个话题。
MARY
这是一个非常有趣的话题。
GEORGE
好的,让我们开始吧。
ROB
这与许多不同的情况有关。
所以,我希望这个输出是:
GEORGE
总词数:12
MARY
总词数:6
ROB
总词数:7
此时,我唯一知道的是我需要创建一个数组,该数组将填充大写名称,然后使用它通过扬声器分隔对话,以便可以计算单词。
我将非常感谢任何帮助,我熟悉数组,但我对字符串分析和操作的经验很少。
答案 0 :(得分:0)
您可能不想使用数组 - Dictionary(Of String, Integer)
是存储每个发言者字数的更好选择。代码可能是这样的事情:
Dim wordCounts As Dictionary(Of String, Integer) = new Dictionary(Of String, Integer)()
Dim currentSpeaker As String = Nothing
For Each line As String In File.ReadLines(dialogueFile)
If line.Trim().Length > 0 AndAlso line.Trim() = line.Trim().ToUpper() Then
' Upper case lines are speakers
currentSpeaker = line.Trim()
Else
If currentSpeaker Is Nothing Then
Throw New Exception("No Speaker!")
End If
Dim wordCount As Integer = line.Split(New String() {" "}, StringSplitOptions.RemoveEmptyEntries).Length
If wordCounts.ContainsKey(currentSpeaker) Then
wordCounts(currentSpeaker) += wordCount
Else
wordCounts.Add(currentSpeaker, wordCount)
End If
End If
Next
For Each count As KeyValuePair(Of String, Integer) In wordCounts
Console.WriteLine("{0}: {1}", count.Key, count.Value)
Next
根据需要输出以下内容:
GEORGE: 12
MARY: 6
ROB: 7