parsingstring并累计正值和负值数字组件
我有一个Excel单元格中的string。
每一行代表一个句子。 这个string代表一个句子中一个单词的正面和负面分数。
句子可以是任意长度的,例如
joy:pos = 0.37 neg = 0.0,诚实:pos = 0.4 neg = 0.0,pick:pos = 0.0 neg = 0.0
hello:pos = 0.0 neg = 0.0,ok:pos = 0.0 neg = 0.0
我想计算单元格中的总正负值。
没有将string与Excel中的文本分割为列function,我不知道一个可能的方法来做一个公式。
这种情况下输出的一个例子是:
pos = 0.77 neg = 0.0
pos = 0.0 neg = 0.0
有任何想法吗?
可能有更好的办法,但我相信这会对你有用:
Function pos(rTest As Range) As String Dim a() As String Dim i As Integer Dim iVal As Double Dim wf As WorksheetFunction Set wf = Application.WorksheetFunction a = Split(rTest, ",") Dim iStart As Integer Dim iEnd As Integer For i = LBound(a) To UBound(a) iStart = wf.Find("=", a(i)) + 1 iEnd = InStr(wf.Find("=", a(i)) + 1, a(i), " ") iVal = iVal + CDbl(Mid(a(i), iStart, iEnd - iStart)) Next pos = "pos=" & CStr(iVal) End Function Function neg(rTest As Range) As String Dim a() As String Dim i As Integer Dim iVal As Double Dim wf As WorksheetFunction Set wf = Application.WorksheetFunction a = Split(rTest, ",") Dim iStart As Integer Dim iEnd As Integer For i = LBound(a) To UBound(a) iStart = InStrRev(a(i), "=") + 1 iEnd = Len(a(i)) + 1 iVal = iVal + CDbl(Mid(a(i), iStart, iEnd - iStart)) Next neg = "neg=" & CStr(iVal) End Function
我仍然认为自己是VBA的新手。 我相信它可以被优化或收紧一点。 把这两个函数放在一个VBA模块中。 然后把=pos
或=neg
作为一个常规公式,并将其放入。
您可以使用RegExp快速parsing,即
Sub Test() Debug.Print StrOut("joy: pos=0.37 neg=0.0, honest: pos=0.4 neg=0.0, pick: pos=0.0 neg=0.0") End Sub
function
Function StrOut(strIn As String) As Variant Dim objRegex As Object Dim objRegexMC As Object Dim objRegexM As Object Dim arr(1) As Variant Set objRegex = CreateObject("vbscript.regexp") With objRegex .Pattern = "(pos|neg)=([0-9]*\.[0-9]+|[0-9]+)" .Global = True If .Test(strIn) Then Set objRegexMC = .Execute(strIn) For Each objRegexM In objRegexMC If objRegexM.submatches(0) = "pos" Then arr(0) = arr(0) + CDbl(objRegexM.submatches(1)) Else arr(1) = arr(1) + CDbl(objRegexM.submatches(1)) End If Next StrOut = arr(0) & " " & arr(1) Else StrOut = "no match" End If End With End Function