[英]Extracting email addresses and names from a text file
我将尽力解释这个问题。 我有一个包含电子邮件地址和名称的文本文件。 看起来像这样: Barb Beney "de.mariof@vienna.aa", "Beny Beney" bet@catering.at
等,都在同一行中。 这只是一个例子,我在一个大文本文件中拥有数千个这样的数据。 我想提取电子邮件和姓名,以便最终得到如下信息:
Beny Beney bet@catering.at-分开,一行一行,没有引号。 最后,它应该从文件中删除所有重复的地址。
我写了提取电子邮件地址的代码,它可以正常工作,但是我不知道如何做剩下的事情。 如何提取名称将其作为地址放在一行中,并消除重复项。 我希望我能正确地描述它,以便您知道我要做什么。 这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.IO;
namespace Email
{
class Program
{
static void Main(string[] args)
{
ExtractEmails(@"C:\Users\drake\Desktop\New.txt", @"C:\Users\drake\Desktop\Email.txt");
}
public static void ExtractEmails(string inFilePath, string outFilePath)
{
string data = File.ReadAllText(inFilePath);
Regex emailRegex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",
RegexOptions.IgnoreCase);
MatchCollection emailMatches = emailRegex.Matches(data);
StringBuilder sb = new StringBuilder();
foreach (Match emailMatch in emailMatches)
{
sb.AppendLine(emailMatch.Value);
}
File.WriteAllText(outFilePath, sb.ToString());
}
}}
欢迎使用此代码,它将适用于通过创建新文件创建的文件,该文件将包含所有重复的电子邮件:
static void Main(string[] args)
{
TextWriter w = File.CreateText(@"C:\Users\drake\Desktop\NonDuplicateEmails.txt");
ExtractEmails(@"C:\Users\drake\Desktop\New.txt", @"C:\Users\drake\Desktop\Email.txt");
TextReader r = File.OpenText(@"C:\Users\drake\Desktop\Email.txt");
RemovingAllDupes(r, w);
}
public static void RemovingAllDupes(TextReader reader, TextWriter writer)
{
string currentLine;
HashSet<string> previousLines = new HashSet<string>();
while ((currentLine = reader.ReadLine()) != null)
{
// Add returns true if it was actually added,
// false if it was already there
if (previousLines.Add(currentLine))
{
writer.WriteLine(currentLine);
}
}
writer.Close();
}
对于新的所需格式,您可以执行以下操作:
private string[] parseEmails(string bigStringiIn){
string[] output;
string bigString;
bigString = bigStringiIn.Replace("\"", "");
output = bigString.Slit(",".ToCharArray());
return output;
}
它使用带有邮件地址的字符串,替换引号,然后将字符串拆分为以下格式的字符串数组: name lastname email@some.com
对于重复的条目删除,嵌套的for应该可以解决问题,检查(也许在.Split()之后)是否匹配字符串。
您还可以对大文件使用以下代码:
static void Main(string[] args)
{
ExtractEmails(@"C:\Users\drake\Desktop\New.txt", @"C:\Users\drake\Desktop\Email.txt");
var sr = new StreamReader(File.OpenRead(@"C:\Users\drake\Desktop\Email.txt"));
var sw = new StreamWriter(File.OpenWrite(@"C:\Users\drake\Desktop\NonDuplicateEmails.txt"));
RemovingAllDupes(sr, sw);
}
public static void RemovingAllDupes(StreamReader str, StreamWriter stw)
{
var lines = new HashSet<int>();
while (!str.EndOfStream)
{
string line = str.ReadLine();
int hc = line.GetHashCode();
if (lines.Contains(hc))
continue;
lines.Add(hc);
stw.WriteLine(line);
}
stw.Flush();
stw.Close();
str.Close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.