将文本文件限制为一个句子或最大字数

时间:2014-03-13 18:20:22

标签: vb.net string text-files line limit

您好我有一个我在VB.NET中工作的程序,它打开一个文本文件并读取一个文本文件,并将每行的单词数量限制为用户设置的任何数量,然后将每行的第一个字母大写。

这是我所拥有的代码,它可以工作;但是,我想更进一步,如果它检测到标点符号如句号或感叹号,则跳转到新行, OR 如果它没有检测到任何标点符号同时将它限制为每行的X字数,就像它已经在做的那样。

这是我到目前为止的代码。

'Limit line to X amount of words

Dim reader As New System.IO.StreamReader(filePath)
Dim textLine As String
Dim count As Integer = MAIN_FORM.wordCountBox.Value
Dim pos As Integer = 0

Do While reader.Peek <> -1

    textLine = reader.ReadLine

    'Split the line to the individual words
    Dim parts = textLine.Split(" "c)
    Do
        'Skip the previous words and take the count required
        Dim block = parts.Skip(pos).Take(count).ToArray

        'position to read the next count words
        pos += count

        If block.Count > 0 Then
            block(0) = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(block(0))
        End If

        MAIN_FORM.previewBox.Items.Add(String.Join(" ", block))

    Loop While (pos < parts.Length)

Loop

例如,如果我将它设置为将每行限制为7个单词,我希望每行只有7个单词,但如果我有一个特定的行,就像这个“三个单词的句子”。虽然这只是3个单词,但小于7的限制,我希望它只是停在那里,因为这是一个完整的句子。

FYI Previewbox是一个常规的列表框控件。

对此的任何帮助将不胜感激。

这是一张图片,解释了我得到的输出。

enter image description here

1 个答案:

答案 0 :(得分:1)

像......那样的东西。

Dim reader As New System.IO.StreamReader(filePath)
Dim textLine As String
Dim count As Integer = MAIN_FORM.wordCountBox.Value
Dim pos As Integer = 0

Do While reader.Peek <> -1

    textLine = reader.ReadLine

    'Split the line to the individual words
    Dim parts = textLine.Split(" "c)
    Do
        'Add check to see if period is there
        Dim Periodfinder As Int32
        For Periodfinder = pos To parts.GetUpperBound(0)
            If parts(Periodfinder).ToString.Contains(".") Then Exit For
        Next
        'set periodfinder to difference between it and pos +1
        Periodfinder = Periodfinder - pos + 1
        'check if it is less than count
        If Periodfinder < count Then count = Periodfinder
        'Skip the previous words and take the count required
        Dim block = parts.Skip(pos).Take(count).ToArray

        'position to read the next count words
        pos += count
        'reset count
        count = MAIN_FORM.wordCountBox.Value

        If block.Count > 0 Then
            block(0) = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(block(0))
        End If

        MAIN_FORM.previewBox.Items.Add(String.Join(" ", block))
        'or if you dont want the period to be carried through
        MAIN_FORM.previewBox.Items.Add(String.Join(" ", block).Replace(".",""))

    Loop While (pos < parts.Length)

Loop

更新代码以允许字符串中有多个句点。

在下面评论的示例中,这将变成一个二三四有五六七八九十进入:

一二三四有五六七七八八十一

和一两三。四五六七。八九十成:

一二三。四四五severn。八八九。

(如果您将限制设置为7个字)
我输出到console.writeline进行测试。

列表框控件中的示例
enter image description here

在某些宽度/高度比率中如果多列设置为True,那么它会将两个条目并排放置而不是一个放在另一个之上!