C# - 重复更改

发布于 2024-11-24 23:08:03 字数 1431 浏览 0 评论 0原文

我有一个如下所示的文件:

R.D.    P.N.      X       Y        Rot  Pkg
L5      120910    64.770  98.425   180  SOP8                    
P4      120911   -69.850  98.425   180  SOIC12                    
L10     120911   -19.685  83.820   180  SOIC10                    
P4      120911    25.400  83.820   180  0603                    
L5      120910    62.484  98.425   180  SOP8
L5      120910    99.100  150.105  180  SOP8
..      ......    ......  ......   ..   .......

我想使用 string.Split() 分割每个字符串,然后检查每行上“string[0]”的第一个值。如果相同的字符串[0]有重复项,我想在字符串[0]的末尾添加一个递增的“-#”。所以它会类似于 string[0] + "-i".....

我的意思是对于 .txt 中的 L5在上面,它们将更改为 L5-1L5-2L5-3P4 也是如此(即 P4-1P4-2)......


因此新的 .txt 将看起来像这样:

R.D.      P.N.      X       Y        Rot  Pkg
L5-1      120910    64.770  98.425   180  SOP8                    
P4-1      120911   -69.850  98.425   180  SOIC12                    
L10       120911   -19.685  83.820   180  SOIC10                    
P4-2      120911    25.400  83.820   180  0603                    
L5-2      120910    62.484  98.425   180  SOP8
L5-3      120910    99.100  150.105  180  SOP8
..      ......    ......  ......   ..   .......

问题:

  • 我怎样才能去做这样的事情?
  • 对理解如何做到这一点有任何帮助吗?

I have a file that looks like this:

R.D.    P.N.      X       Y        Rot  Pkg
L5      120910    64.770  98.425   180  SOP8                    
P4      120911   -69.850  98.425   180  SOIC12                    
L10     120911   -19.685  83.820   180  SOIC10                    
P4      120911    25.400  83.820   180  0603                    
L5      120910    62.484  98.425   180  SOP8
L5      120910    99.100  150.105  180  SOP8
..      ......    ......  ......   ..   .......

I would like to use string.Split() to split each string up and then check the first value of the "string[0]" on every line. If there are duplicates of the same string[0] I would like to add an incremented "-#" to the end of the string[0]. So it would be something like string[0] + "-i".....

What I mean by this is that for the L5's in the .txt above, they would be changed to L5-1,L5-2,L5-3. The same goes with the P4's (ie, P4-1,P4-2)....


So the new .txt would look like this:

R.D.      P.N.      X       Y        Rot  Pkg
L5-1      120910    64.770  98.425   180  SOP8                    
P4-1      120911   -69.850  98.425   180  SOIC12                    
L10       120911   -19.685  83.820   180  SOIC10                    
P4-2      120911    25.400  83.820   180  0603                    
L5-2      120910    62.484  98.425   180  SOP8
L5-3      120910    99.100  150.105  180  SOP8
..      ......    ......  ......   ..   .......

QUESTIONS:

  • How can I go about doing such a thing?
  • Any help on understand how to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

娇柔作态 2024-12-01 23:08:03

如果您可以接受仅包含一次出现的所有值的 -1,这里有一个示例程序。您必须在最后制作一份副本,因为在写入新文件时无法删除原始文件。

// Replace c:\temp\temp.txt with you original file.
// Replace c:\temp\temp2.txt with your temporary new file.

using (var r = new StreamReader(@"c:\temp\temp.txt"))
{
    using (var w = new StreamWriter(@"c:\temp\temp2.txt"))
    {
        string line;
        var counter = new Dictionary<string, int>();

        // write header first, no changes necessary
        if ((line = r.ReadLine()) != null)
        {
            w.WriteLine(line);
        }

        while ((line = r.ReadLine()) != null)
        {

            // assuming it is safe to split on a space
            var values = line.Split(' ');

            // if the value hasn't been encountered before, add it
            if (!counter.ContainsKey(values[0]))
            {
                // start counter at 0
                counter.Add(values[0], 0);
            }

            // increment the count as we hit each occurrence of the
            // given key
            counter[values[0]] = counter[values[0]] + 1;

            // write out the original line, replacing the key with the
            // format key-#
            w.WriteLine(line.Replace(values[0], 
                                     string.Format("{0}-{1}", 
                                                   values[0], 
                                                   counter[values[0]])));
        }
    }
}

示例输入:

R.D.    P.N.      X       Y        Rot  Pkg
L5      120910    64.770  98.425   180  SOP8                    
P4      120911   -69.850  98.425   180  SOIC12                    
L10     120911   -19.685  83.820   180  SOIC10                    
P4      120911    25.400  83.820   180  0603                    
L5      120910    62.484  98.425   180  SOP8
L5      120910    99.100  150.105  180  SOP8

示例输出(已测试):

R.D.    P.N.      X       Y        Rot  Pkg
L5-1    120910    64.770  98.425   180  SOP8                    
P4-1    120911   -69.850  98.425   180  SOIC12                    
L10-1   120911   -19.685  83.820   180  SOIC10                    
P4-2    120911    25.400  83.820   180  0603                    
L5-2    120910    62.484  98.425   180  SOP8
L5-3    120910    99.100  150.105  180  SOP8

如果您不想要 -1,您始终可以在写入之前进行检查以确保计数 > 1.

If you are ok with having a -1 for all values that only contain one occurrence, here is a samples program. You'd have to do a copy at the end, since you can't delete the original file while writing the new one.

// Replace c:\temp\temp.txt with you original file.
// Replace c:\temp\temp2.txt with your temporary new file.

using (var r = new StreamReader(@"c:\temp\temp.txt"))
{
    using (var w = new StreamWriter(@"c:\temp\temp2.txt"))
    {
        string line;
        var counter = new Dictionary<string, int>();

        // write header first, no changes necessary
        if ((line = r.ReadLine()) != null)
        {
            w.WriteLine(line);
        }

        while ((line = r.ReadLine()) != null)
        {

            // assuming it is safe to split on a space
            var values = line.Split(' ');

            // if the value hasn't been encountered before, add it
            if (!counter.ContainsKey(values[0]))
            {
                // start counter at 0
                counter.Add(values[0], 0);
            }

            // increment the count as we hit each occurrence of the
            // given key
            counter[values[0]] = counter[values[0]] + 1;

            // write out the original line, replacing the key with the
            // format key-#
            w.WriteLine(line.Replace(values[0], 
                                     string.Format("{0}-{1}", 
                                                   values[0], 
                                                   counter[values[0]])));
        }
    }
}

Sample input:

R.D.    P.N.      X       Y        Rot  Pkg
L5      120910    64.770  98.425   180  SOP8                    
P4      120911   -69.850  98.425   180  SOIC12                    
L10     120911   -19.685  83.820   180  SOIC10                    
P4      120911    25.400  83.820   180  0603                    
L5      120910    62.484  98.425   180  SOP8
L5      120910    99.100  150.105  180  SOP8

Sample output (tested):

R.D.    P.N.      X       Y        Rot  Pkg
L5-1    120910    64.770  98.425   180  SOP8                    
P4-1    120911   -69.850  98.425   180  SOIC12                    
L10-1   120911   -19.685  83.820   180  SOIC10                    
P4-2    120911    25.400  83.820   180  0603                    
L5-2    120910    62.484  98.425   180  SOP8
L5-3    120910    99.100  150.105  180  SOP8

If you don't want the -1, you can always do a check before the write to ensure that the count is > 1.

み青杉依旧 2024-12-01 23:08:03

我会怎么做:

  1. 打开文件进行读取,打开另一个文件进行写入。
  2. 从原始文件中读取标头,写入新文件。
  3. 创建空字符串到 int 字典。
  4. 开始循环:
  5. 读取行,拆分名称。
  6. 如果字典中不存在该名称,则将其作为整数值为 1 的键添加到字典中。
  7. 附加给定名称的名称 + 字典值(例如,名称为“L5”,整数为 3,因此将“L5-3”)和该行的其余内容(从步骤 5 保存)添加到新文件中。
  8. 增加给定名称的字典值。
  9. 从步骤 4 开始重复。
  10. 删除旧文件,更改新文件名以匹配先前的文件。

编辑字典示例:

//Create an empty dictionary
Dictionary<string, int> dictionary = new Dictionary<string, int>();

//Add a key/value pair
dictionary.Add("L5", 1);

//Check if the value exists, if not then add it
if( !dictionary.ContainsKey("L9") )
    dictionary.Add("L9", 1);

//Get the value (after making sure the value exists)
int value = dictionary["L5"];

//Increment the value
dictionary["L5"] = value + 1;

如果您知道字典已经包含该键,则应该仅使用 dictionary[string] 语法,否则您可能会遇到错误。另一种方法是使用 TryGetValue 方法:

int value;
if( dictionary.TryGetValue("L5", out value) )
{
    //Key exists already
    Console.WriteLine("L5 has a value of {0}", value);
}
else
{
    //Key does not exist
    dictionary.Add("L5", 1);
}

How I would do it:

  1. Open file to read, open another file to write to.
  2. Read header from original file, write to new file.
  3. Create empty string to int dictionary.
  4. Begin loop:
  5. Read line, split out name.
  6. If the name doesn't exist in the dictionary, add it to the dictionary as a key with an integer value of 1.
  7. Append the name + dictionary value for the given name (eg, name is "L5", integer is 3, so append "L5-3") and the rest of the contents of the line (saved from step 5) to the new file.
  8. Increment dictionary value for given name.
  9. Repeat from step 4.
  10. Delete old file, change new file name to match previous file.

Edit for dictionary example:

//Create an empty dictionary
Dictionary<string, int> dictionary = new Dictionary<string, int>();

//Add a key/value pair
dictionary.Add("L5", 1);

//Check if the value exists, if not then add it
if( !dictionary.ContainsKey("L9") )
    dictionary.Add("L9", 1);

//Get the value (after making sure the value exists)
int value = dictionary["L5"];

//Increment the value
dictionary["L5"] = value + 1;

You should only use the dictionary[string] syntax if you know the dictionary already includes that key, otherwise you risk getting an error. Another way to do it is to use the TryGetValue method:

int value;
if( dictionary.TryGetValue("L5", out value) )
{
    //Key exists already
    Console.WriteLine("L5 has a value of {0}", value);
}
else
{
    //Key does not exist
    dictionary.Add("L5", 1);
}
日记撕了你也走了 2024-12-01 23:08:03

这个怎么样:

 string[] input = {"R.D.    P.N.      X       Y        Rot  Pkg",
"L5 120910    64.770  98.425   180  SOP8",
"P4      120911   -69.850  98.425   180  SOIC12",
"L10     120911   -19.685  83.820   180  SOIC10",
"P4      120911    25.400  83.820   180  0603",
"L5      120910    62.484  98.425   180  SOP8",
"L5      120910    99.100  150.105  180  SOP8"};

    var control = new Dictionary<string, int>();
    var result = new List<string[]>();

    foreach (var line in input)
    {
       var array = line.Split(' ');
       result.Add(array);
       int occurencies = 0;
       ;
       control[array[0]] = control.TryGetValue(array[0], out occurencies) 
                           ? occurencies == 1 ? -2 : occurencies - 1
                           : 1;
    }

    foreach (var item in result.AsEnumerable().Reverse())
    {
       int value = control[item[0]];
       if (value < 0)
       {
          control[item[0]] = value + 1;
          item[0] = item[0] + value;     
       }
    }

这会给你你想要的结果。可能有更有效的方法,但是,对于 800 行来说,这应该足够了。

How about this one:

 string[] input = {"R.D.    P.N.      X       Y        Rot  Pkg",
"L5 120910    64.770  98.425   180  SOP8",
"P4      120911   -69.850  98.425   180  SOIC12",
"L10     120911   -19.685  83.820   180  SOIC10",
"P4      120911    25.400  83.820   180  0603",
"L5      120910    62.484  98.425   180  SOP8",
"L5      120910    99.100  150.105  180  SOP8"};

    var control = new Dictionary<string, int>();
    var result = new List<string[]>();

    foreach (var line in input)
    {
       var array = line.Split(' ');
       result.Add(array);
       int occurencies = 0;
       ;
       control[array[0]] = control.TryGetValue(array[0], out occurencies) 
                           ? occurencies == 1 ? -2 : occurencies - 1
                           : 1;
    }

    foreach (var item in result.AsEnumerable().Reverse())
    {
       int value = control[item[0]];
       if (value < 0)
       {
          control[item[0]] = value + 1;
          item[0] = item[0] + value;     
       }
    }

This will give you the result you are after. There may be more efficient ways, but, for 800 lines this should be good enough.

留蓝 2024-12-01 23:08:03

800 行是相当小的。

  1. 遍历数组,并将第一列添加到字典中。在添加到字典之前测试一下该值是否出现在其中。如果是,只需增加计数器即可。

  2. 查一下你的字典。对于每个值大于 1 的键,循环数组并将“-1”、“-2”等附加到该键的所有出现位置。 ..

效率不是很高,但很容易实现

800 lines is pretty tiny.

  1. Go through the array, and add the first column to a dictionary. Before adding to the dictionary test to see if the value apperas in it. If it does, just increment the counter.

  2. Go through your dictionary. For each key whose value is greater than 1, cycle the array and append "-1", "-2", etc to all occurrences of the key. ..

Not very efficient, but pretty easy to implement

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文