交换文本文件中的动态行数
本文关键字:动态 文本 文件 交换 | 更新日期: 2023-09-27 17:57:30
我有很多带值的文本文件,尽管文本文件中的行应该部分加扰。
文本文件的示例如下:(请参阅编辑以获得更简单的示例)
0.00;1.2;3;2015-20-06 13:33:33
0.00;1.2;3;2015-20-06 13:33:34
0.00;1.2;3;2015-20-06 13:33:35
0.00;1.2;3;2015-20-06 13:33:36
[RAND]
0.00;1.2;3;2015-20-06 12:05:05
0.00;1.2;3;2015-20-06 12:05:22
0.00;1.2;3;2015-20-06 12:06:27
0.00;1.2;3;2015-20-06 12:05:42
[/RAND]
0.00;1.2;3;2015-20-06 12:25:36
0.00;1.8;3;2015-20-06 12:26:26
0.00;1.2;3;2015-20-06 12:28:05
[RAND]
0.00;1.8;3;2015-20-06 12:32:22
0.00;1.2;3;2015-20-06 12:33:04
[/RAND]
CCD_ 1和CCD_。到目前为止,我有以下内容,但我完全不知道如何从这里继续下去,也不知道这是否是正确的方法。
using (StreamReader reader = new StreamReader(LocalFile))
{
bool InRegion = false;
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.Equals("[RAND]"))
InRegion = true;
if (line.Equals("[/RAND]"))
InRegion = false;
}
}
我担心的一个问题是,我正在使用StreamReader,因此无法更改文件。
RAND
块和每个文件的多个RAND
块内可以有2行,但也可以有10行。有人能给我解释一下这个怎么走吗?
提前非常感谢。
编辑:
更简单的例子:
A
B
C
[RAND]
D
E
F
[/RAND]
G
H
然后,它应该以随机顺序打乱D、E和F的行,这样你就可以得到如下结果:
A
B
C
E
F
D
G
H
导致大多数代码(尽管可读)的"庞大"方式是:
- 读取所有行,关闭文件
- 查找要随机化的块
- 将这些块随机化
- 将结果写入新文件
- 将新文件移到旧文件上
类似这样的东西:
var linesInFile = File.ReadAllLines();
var newLines = new List<string>();
var toRandomize = new List<string>();
bool inRegion = false;
for (int i = 0; i < linesInFile.Count; i++)
{
string line = linesInFile[i];
if (line == "[RAND]")
{
inRegion = true;
continue;
}
if (line == "[/RAND]")
{
inRegion = false;
// End of random block.
// Now randomize `toRandomize`, add it to newLines and clear it
newLines.AddRange(toRandomize);
toRandomize.Clear();
continue;
}
if (inRegion)
{
toRandomize.Add(line);
}
else
{
newLines.Add(line);
}
}
File.WriteAllLines(newLines, ...);
请参见随机化列表<T>以随机化列表。
我认为这对有好处
一次读取文件的所有文本
并使用正则表达式获得随机区域
并用它替换随机化结果
以上步骤可以通过RegEx
类的Replace
方法来完成
并最终将新内容保存到文件
例如:
var regExp = @"('[RAND'])('w|'s|'d)*('[/RAND'])";
var res = Regex.Replace(str, regExp, match =>
{
// suffle the and return result
// the return string replaced with occuring rand area
// for example with suffle algorithms
return "Randomized";
});