gpt4 book ai didi

c# - 替换大文本文件中的长列表单词

转载 作者:太空狗 更新时间:2023-10-30 00:56:04 25 4
gpt4 key购买 nike

我需要一个快速的方法来处理大文本文件

我有2个文件,一个大文本文件(~20Gb)和另一个包含约 1200 万个组合词列表的文本文件

我想找到第一个文本文件中的所有组合词并用另一个组合词替换它(带下划线的组合词)

示例“计算机信息”>替换为>“Computer_Information”

我使用此代码,但性能很差(我在具有 16Gb Ram 和 16 核的 Hp G7 服务器上测试)

public partial class Form1 : Form
{
HashSet<string> wordlist = new HashSet<string>();

private void loadComboWords()
{
using (StreamReader ff = new StreamReader(txtComboWords.Text))
{
string line;
while ((line = ff.ReadLine()) != null)
{
wordlist.Add(line);
}
}
}

private void replacewords(ref string str)
{

foreach (string wd in wordlist)
{
// ReplaceEx(ref str,wd,wd.Replace(" ","_"));
if (str.IndexOf(wd) > -1)
str.Replace(wd, wd.Replace(" ", "_"));
}
}

private void button3_Click(object sender, EventArgs e)
{
string line;
using (StreamReader fread = new StreamReader(txtFirstFile.Text))
{
string writefile = Path.GetFullPath(txtFirstFile.Text) + Path.GetFileNameWithoutExtension(txtFirstFile.Text) + "_ReplaceComboWords.txt";
StreamWriter sw = new StreamWriter(writefile);
long intPercent;
label3.Text = "initialing";
loadComboWords();

while ((line = fread.ReadLine()) != null)
{
replacewords(ref line);
sw.WriteLine(line);

intPercent = (fread.BaseStream.Position * 100) / fread.BaseStream.Length;
Application.DoEvents();
label3.Text = intPercent.ToString();
}
sw.Close();
fread.Close();
label3.Text = "Finished";
}
}
}

在合理的时间内完成这项工作的任何想法

谢谢

最佳答案

乍一看,您采用的方法看起来不错 - 它应该可以正常工作,并且没有什么明显的原因会导致例如大量垃圾收集。

我认为最主要的是您只会使用这 16 个内核中的一个:没有任何东西可以在其他 15 个内核之间分担负载。

认为最简单的方法是将 20Gb 的大文件分成 16 个 block ,然后一起分析每个 block ,然后再次将这些 block 合并回一起。与一起扫描这 16 个 block 所涉及的大约 16 倍增益相比,拆分和重新组合文件所花费的额外时间应该是最小的。

概括地说,一种方法可能是:

    private List<string> SplitFileIntoChunks(string baseFile)
{
// Split the file into chunks, and return a list of the filenames.
}

private void AnalyseChunk(string filename)
{
// Analyses the file and performs replacements,
// perhaps writing to the same filename with a different
// file extension
}

private void CreateOutputFileFromChunks(string outputFile, List<string> splitFileNames)
{
// Combines the rewritten chunks created by AnalyseChunk back into
// one large file, outputFile.
}

public void AnalyseFile(string inputFile, string outputFile)
{
List<string> splitFileNames = SplitFileIntoChunks(inputFile);

var tasks = new List<Task>();
foreach (string chunkName in splitFileNames)
{
var task = Task.Factory.StartNew(() => AnalyseChunk(chunkName));
tasks.Add(task);
}

Task.WaitAll(tasks.ToArray());

CreateOutputFileFromChunks(outputFile, splitFileNames);
}

一个小细节:将流长度的计算移出循环,您只需要获取一次。

编辑:另外,包括@Pavel Gatilov 的想法以反转内部循环的逻辑并搜索 1200 万列表中行中的每个单词。

关于c# - 替换大文本文件中的长列表单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8620238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com