我将假设您的输入文件在实际文本中可能包含逗号,而不仅仅是分隔两个字段。
现在,如果是这样的话,那么标准的 CSV 文件格式可以像这样格式化文件:
Laughing Out Loud,LOL
"I Came, I Saw, I Conquered",ICISIC
但是,从您的示例中,您在“LOL”之前有一个 空格,因此您似乎没有使用标准 CSV。
所以我会处理这个输入:
Laughing Out Loud, LOL
"I Came, I Saw, I Conquered",ICISIC
"to, too, or two", 2
because,B/C
对于这个输入,这段代码会产生一个字典:
var dictionary =
(
from line in File.ReadAllLines("FILE.CSV")
let lastComma = line.LastIndexOf(',')
let abbreviation = line.Substring(lastComma + 1).Trim()
let actualRaw = line.Substring(0, lastComma).Trim()
let actual = actualRaw.StartsWith("\"") && actualRaw.EndsWith("\"")
? actualRaw.Substring(1, actualRaw.Length - 2)
: actualRaw
select new { abbreviation, actual }
).ToDictionary(x => x.abbreviation, x => x.actual);
不过,你可以比这更好。很有可能创建一个“超级功能”,它会一次性为您完成所有替换。
试试这个:
var translate =
(
from line in File.ReadAllLines("FILE.CSV")
let lastComma = line.LastIndexOf(',')
let abbreviation = line.Substring(lastComma + 1).Trim()
let actualRaw = line.Substring(0, lastComma).Trim()
let actual = actualRaw.StartsWith("\"") && actualRaw.EndsWith("\"")
? actualRaw.Substring(1, actualRaw.Length - 2)
: actualRaw
select (Func<string, string>)(x => x.Replace(abbreviation, actual))
).Aggregate((f1, f2) => x => f2(f1(x)));
那么我可以这样做:
Console.WriteLine(translate("It was me 2 B/C ICISIC, LOL!"));
我得到这个结果:
我也是,或者两个,因为我来了,我看到了,我征服了,大声笑了!