我有两个包含各种列的文本文件,每列用一个标签(“”)分隔。我想要做的是以下几点: -
如果文本文件2第1列中的值在文本文件1第1列中不包含任何值,则将该字段添加到文本文件2中,并将第1列添加1,如下所示
String 1
如果文本文件2第1列中的值已经出现在文本文件1列1中,则只需向该值添加+1,因此如果上述值已经在文本文件1列1和文本文件2列中1然后它会显示为。
String 2
如果它再次发生那么
String 3
等等。
到目前为止,我有以下编码。
Dim lines1 As New List(Of String)(IO.File.ReadAllLines("File1"))
Dim lines2 As New List(Of String)(IO.File.ReadAllLines("File2"))
IO.File.WriteAllLines("File2", lines1.ToArray) & +1)
更新
Dim lines1 As New List(Of String)(IO.File.ReadAllLines("D:\Test\File6.txt"))
Dim lines2 As New List(Of String)(IO.File.ReadAllLines("D:\Test\File5.txt"))
Dim values As New Dictionary(Of String, Integer)()
For Each line As String In lines1
Dim fields() As String = line.Split(" "c)
If fields.Length > 1 Then
values(fields(0)) = Integer.Parse(fields(1))
End If
Next
For Each line As String In lines2
Dim fields() As String = line.Split(" "c)
If fields.Length > 0 Then
If values.ContainsKey(fields(0)) Then
values(fields(0)) = values(fields(0)) + 1
Else
values(fields(0)) = 1
End If
End If
Next
lines1.Clear()
For Each pair As KeyValuePair(Of String, Integer) In values
lines1.Add(pair.Key + " " + pair.Value.ToString())
Next
IO.File.WriteAllLines("D:\Test\File6.txt", lines1.ToArray)
我使用上面的编码,但它删除了第二列?
答案 0 :(得分:1)
我建议使用字典在第一个文本文件中存储键/值对。然后,在解析第二个文本文件中的数据时,可以轻松地搜索和修改字典中的数据。例如:
Dim lines1 As New List(Of String)(New String() {"A a 1", "B b 2", "C c 3"})
Dim lines2 As New List(Of String)(New String() {"A a", "D d"})
Dim values As New Dictionary(Of String, Integer)()
For Each line As String In lines1
Dim fields() As String = line.Split(" "c)
If fields.Length > 2 Then
values(fields(0) + " " + fields(1)) = Integer.Parse(fields(2))
End If
Next
For Each line As String In lines2
Dim fields() As String = line.Split(" "c)
If fields.Length > 1 Then
Dim key As String = fields(0) + " " + fields(1)
If values.ContainsKey(key) Then
values(key) = values(key) + 1
Else
values(key) = 1
End If
End If
Next
lines1.Clear()
For Each pair As KeyValuePair(Of String, Integer) In values
lines1.Add(pair.Key + " " + pair.Value.ToString())
Next