2013-02-26 31 views
0

我正在構建一個程序,通過掃描其書名頁並使用OCR來獲取本書的出版商...因爲出版商總是處於標題頁的底部,所以我認爲由空間分隔的檢測線是解決方案,但我不知道如何測試。這裏是我的代碼:如何檢查字符串中的行是否由空格分隔?

Dim builder As New StringBuilder() 
Dim reader As New StringReader(txtOCR.Text) 
Dim iCounter As Integer = 0 
While True 
    Dim line As String = reader.ReadLine() 
    If line Is Nothing Then Exit While 

    'i want to put the condition here 

End While 
txtPublisher.Text = builder.ToString() 
+0

@Konrad魯道夫感謝編輯我的問題我很抱歉,如果我不能解釋清楚.. :) – user2107624 2013-02-26 10:00:43

回答

2

你的意思是空行嗎?然後,你可以這樣做:

Dim bEmpty As Boolean 

然後在循環中:

If line.Trim().Length = 0 Then 
    bEmpty = True 
Else 
    If bEmpty Then 
     '... 
    End If 

    bEmpty = False 
End If 
+0

感謝,但我的問題是後檢測第二個空行如何將可能是發佈者的下一行存儲到文本框? – user2107624 2013-02-26 09:58:04

+0

@ user2107624您可以在每一行上循環,您可以使用布爾值來確定最後一行是否爲空。我編輯我的答案。 – SysDragon 2013-02-26 09:59:46

+0

我想我現在知道了謝謝@SysDragon如果問問小老虎的問題,很抱歉,但非常感謝你的幫助:) – user2107624 2013-02-26 10:04:06

1

爲什麼不能做到以下幾點:從底部走,直到你找到的第一個非空行(不知道OCR是如何工作的......也許最底部的行總是非空的,在這種情況下這是多餘的)。在下一步中,直到第一個空行。中間的文字是出版商。

你不需要StringReader爲:

Dim lines As String() = txtOCR.Text.Split(Environment.NewLine) 
Dim bottom As Integer = lines.Length - 1 

' Find bottom-most non-empty line. 
Do While String.IsNullOrWhitespace(lines(bottom)) 
    bottom -= 1 
Loop 

' Find empty line above that 
Dim top As Integer = bottom - 1 

Do Until String.IsNullOrWhitespace(lines(top)) 
    top -= 1 
Loop 

Dim publisherSubset As New String(bottom - top)() 
Array.Copy(lines, top + 1, publisherSubset, 0, bottom - top) 
Dim publisher As String = String.Join(Environment.NewLine, publisherSubset) 

但說實話,我不認爲這是一個特別好的辦法。它不靈活,不能很好地處理意外的格式。我會使用正則表達式來描述發佈者字符串(及其上下文)的外觀。也許這還不夠,你必須考慮描述整個頁面來推斷哪些位是發佈者。

+0

是的,這只是我的一個條件謝謝你的建議..我會嘗試代碼.. bottom-大多數行是一個空行,如何ocr工作我認爲 – user2107624 2013-02-26 10:14:00

1

假設發佈者總是在最後一行,並且總是出現在空行之後。那麼下面可能是?

Dim Lines as New List(Of String) 
    Dim currentLine as String = "" 
    Dim previousLine as String = "" 

    Using reader As StreamReader = New StreamReader(txtOCR.Txt) 
    currentLine = reader.ReadLine 
    If String.IsNullOrWhiteSpace(previousLine) then lines.Add(currentLine) 
    previousLine = currentLine 
    End Using 

    txtPublisher.Text = lines.LastOrDefault() 

要忽略,如果以前的行是空/空:

Dim Lines as New List(Of String) 
Using reader As StreamReader = New StreamReader(txtOCR.Txt) 
lines.Add(reader.ReadLine) 
End Using 

txtPublisher.Text = lines.LastOrDefault() 
+0

您的代碼獲取第一行不是最後一行.. – user2107624 2013-02-26 10:30:15

+0

它可能會返回第一行的唯一方法是如果沒有其他行在txt文件前面有一個空白/空行預先。我編輯了我的答案,以包含以下情況:如果您想要txt的最後一行,而不管前面的行是什麼。 – freschx 2013-02-26 11:00:01

相關問題