gpt4 book ai didi

c# - 如何解析具有交替名称行和整数列表的文本文件?

转载 作者:太空宇宙 更新时间:2023-11-03 19:43:35 28 4
gpt4 key购买 nike

我需要读取一个文件并将该数据放入不同的数组中。

我的 .txt 文件如下所示:

w1;
1 2 3
w2;
3 4 5
w3;
4 5 6

我试过类似下面的方法:

int[] w1 = new int [3];
int[] w2 = new int [3];
int[] w3 = new int [3];

string v = "w1:|w2:|w3:";
foreach (string line in File.ReadAllLines(@"D:\\Data.txt"))
{
string[] parts = Regex.Split(line, v);

我得到了那个字符串,但我不知道如何将它的每个元素切割成上面显示的数组。

最佳答案

而不是解析文件并将数组放入对应于硬编码名称的三个硬编码变量中 w1 , w2w3 , 我会删除硬编码并将文件解析为 Dictionary<string, int[]>像这样:

public static class DataFileExtensions
{
public static Dictionary<string, int[]> ParseDataFile(string fileName)
{
var separators = new [] { ' ' };
var query = from pair in File.ReadLines(fileName).Chunk(2)
let key = pair[0].TrimEnd(';')
let value = (pair.Count < 2 ? "" : pair[1]).Split(separators, StringSplitOptions.RemoveEmptyEntries).Select(s => int.Parse(s, NumberFormatInfo.InvariantInfo)).ToArray()
select new { key, value };
return query.ToDictionary(p => p.key, p => p.value);
}
}

public static class EnumerableExtensions
{
// Adapted from the answer to "Split List into Sublists with LINQ" by casperOne
// https://stackoverflow.com/questions/419019/split-list-into-sublists-with-linq/
// https://stackoverflow.com/a/419058
// https://stackoverflow.com/users/50776/casperone
public static IEnumerable<List<T>> Chunk<T>(this IEnumerable<T> enumerable, int groupSize)
{
// The list to return.
List<T> list = new List<T>(groupSize);

// Cycle through all of the items.
foreach (T item in enumerable)
{
// Add the item.
list.Add(item);

// If the list has the number of elements, return that.
if (list.Count == groupSize)
{
// Return the list.
yield return list;

// Set the list to a new list.
list = new List<T>(groupSize);
}
}

// Return the remainder if there is any,
if (list.Count != 0)
{
// Return the list.
yield return list;
}
}
}

您将按如下方式使用它:

var dictionary = DataFileExtensions.ParseDataFile(fileName);

Console.WriteLine("Result of parsing {0}, encountered {1} data arrays:", fileName, dictionary.Count);
foreach (var pair in dictionary)
{
var name = pair.Key;
var data = pair.Value;

Console.WriteLine(" Data row name = {0}, values = [{1}]", name, string.Join(",", data));
}

哪些输出:

Result of parsing Question49341548.txt, encountered 3 data arrays:
Data row name = w1, values = [1,2,3]
Data row name = w2, values = [3,4,5]
Data row name = w3, values = [4,5,6]

注意事项:

sample 加工 .Net fiddle .

关于c# - 如何解析具有交替名称行和整数列表的文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49341548/

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