跳过特定单词的行
Skip line with specific word
我的 .txt 文件有问题。
除了一个说 "Kleur" 和另一个说 "Binair".
之外,它里面有相同的文字
我需要阅读该 .txt 文件中的所有行,但需要跳过其中包含单词 "kleur" 的行。
这是我的代码示例:
For Each f In dinfo.GetFiles("*.txt", SearchOption.AllDirectories)
Using sr As New StreamReader(f.FullName)
Dim findstring = IO.File.ReadAllText(f.FullName)
Dim Lookfor As String = "Binair"
If findstring.Contains(Lookfor) Then
End If
但这并没有跳过 kleur 行,代码仍然对它起作用。
谁能帮我跳过这些行,只使用其中的 "binair" 行?
如果你想逐行应用一些逻辑跳过不需要的行,然后逐行读取文件或在内存中读取它们后一次处理这些行(选择取决于文件大小)
此方法在 ReadLines 返回的行上使用 IEnumerable 扩展 Where(returns 您的行的 IEnumerable 并且不会将它们全部加载到内存中)。
For Each f In dinfo.GetFiles("*.txt", SearchOption.AllDirectories)
Dim lines = File.ReadLines(f.FullName).
Where(Function(x) Not x.Contains("Kleur"))
' lines contains only the lines without the word Kleur
For Each l As String In lines
' Process the lines
Next
Next
但您也可以使用 StreamReader 读取单行,根据需要进行处理,然后循环读取下一行
Dim line As String = ""
For Each f In dinfo.GetFiles("*.txt", SearchOption.AllDirectories)
Using sr = New StreamReader(f.FullName)
While True
line = sr.ReadLine
If line IsNot Nothing Then
If Not line.Contains("Kleur") Then
' process the line
End If
Else
Exit While
End If
End While
End Using
Next
最后你可以加载内存中的所有内容并从那里处理(但要注意文件的大小)
Dim line As String = ""
For Each f In dinfo.GetFiles("*.txt", SearchOption.AllDirectories)
Dim lines = File.ReadAllLines(f.FullName)
For each line in lines
if Not line.Contains("Kleur") Then
' process the line
End If
Next
Next
我的 .txt 文件有问题。 除了一个说 "Kleur" 和另一个说 "Binair".
之外,它里面有相同的文字我需要阅读该 .txt 文件中的所有行,但需要跳过其中包含单词 "kleur" 的行。
这是我的代码示例:
For Each f In dinfo.GetFiles("*.txt", SearchOption.AllDirectories)
Using sr As New StreamReader(f.FullName)
Dim findstring = IO.File.ReadAllText(f.FullName)
Dim Lookfor As String = "Binair"
If findstring.Contains(Lookfor) Then
End If
但这并没有跳过 kleur 行,代码仍然对它起作用。
谁能帮我跳过这些行,只使用其中的 "binair" 行?
如果你想逐行应用一些逻辑跳过不需要的行,然后逐行读取文件或在内存中读取它们后一次处理这些行(选择取决于文件大小)
此方法在 ReadLines 返回的行上使用 IEnumerable 扩展 Where(returns 您的行的 IEnumerable 并且不会将它们全部加载到内存中)。
For Each f In dinfo.GetFiles("*.txt", SearchOption.AllDirectories)
Dim lines = File.ReadLines(f.FullName).
Where(Function(x) Not x.Contains("Kleur"))
' lines contains only the lines without the word Kleur
For Each l As String In lines
' Process the lines
Next
Next
但您也可以使用 StreamReader 读取单行,根据需要进行处理,然后循环读取下一行
Dim line As String = ""
For Each f In dinfo.GetFiles("*.txt", SearchOption.AllDirectories)
Using sr = New StreamReader(f.FullName)
While True
line = sr.ReadLine
If line IsNot Nothing Then
If Not line.Contains("Kleur") Then
' process the line
End If
Else
Exit While
End If
End While
End Using
Next
最后你可以加载内存中的所有内容并从那里处理(但要注意文件的大小)
Dim line As String = ""
For Each f In dinfo.GetFiles("*.txt", SearchOption.AllDirectories)
Dim lines = File.ReadAllLines(f.FullName)
For each line in lines
if Not line.Contains("Kleur") Then
' process the line
End If
Next
Next