2011-02-27 8 views
1

이것은 처리해야하는 텍스트 파일의 추출물입니다. 수행해야 할 일은 프로그램 이이 텍스트 파일을 읽고 스펙으로 형식화해야합니다. 문제는 내가 많은 experiance 텍스트 파일과 작업을하지 않습니다. 이것은 샘플 입력 파일입니다. 처리 할 때C에서 배열로 텍스트 파일 읽기

BSA  Security Definition - Operator Report Type 28 


NBC 3RD QUARTER PROFILE REVIEW 2010 
________________________________________________________________________________   


Operator:     ABAZ095  
Number of entries:  149 
User selection:   Selected Items   

________________________________________________________________________________   


Search Criteria :- 

    Operator Name = BT% 
    Approval Status = Any 
    Enable Status = Any 
    One-time Pwd = Any 
    Profiles  = 
    Units   = 
    Printers  = 
    Terminals  = 

________________________________________________________________________________   

Operator ID   = BTA020   

Name     = ASIA CHAMBEGA 
Active profile  = User_Disabled 
Enable status   = Disabled   
Re-enable date  = 31/12/36 00:00:00   
Approval status  = Approved   
Last changed   = 21/07/10 07:34:30  
Last sign-on   = 13/06/08 14:09:37   
Calculated pwd  = BD    
One-time password  = No    
Assigned unit   = None    



Operator ID   = BTAC002   

Name     = A KALATA (NBC) 
Active profile  = User_Disabled 
Enable status   = Disabled   
Re-enable date  = 31/12/36 00:00:00   
Approval status  = Approved   
Last changed   = 31/05/10 14:04:41  
Last sign-on   = n/a 
Calculated pwd  = B9    
One-time password  = No    
Assigned unit   = None    



Operator ID   = BTAK000   

Name     = AISHA KEJO  
Active profile  = NLCB_R6.0_ACCESSCTRL  
Active profile  = NLCB_R6.0_VERAUT_MBE  
Enable status   = Enabled   
Re-enable date  = n/a 
Approval status  = Approved   
Last changed   = 12/07/08 08:10:47  
Last sign-on   = 19/07/08 08:08:58   
Calculated pwd  = 8A    
One-time password  = No    
Assigned unit   = NLCB    



Operator ID   = BTAL001   

Name     = AMANDUS LIPILI 
Active profile  = User_Disabled 
Enable status   = Disabled   
Re-enable date  = 31/12/36 00:00:00   
Approval status  = Approved   
Last changed   = 01/07/10 08:39:03  
Last sign-on   = 11/11/09 08:25:07   
Calculated pwd  = 4B    
One-time password  = No    
Assigned unit   = None    

는 다음과 같이 보일 것입니다 출력 파일은 다음과 같습니다 당신이 볼 수 있듯이

BTAK000, AISHA KEJO, NLCB_R6.0_ACCESSCTRL 
BTAK000, AISHA KEJO, NLCB_R6.0_VERAUT_MBE 

는 모든 데이터에 있지만 운영자 ID는 이름과 활성 프로파일을 출력 할 필요가 당겨해야 . 파일에 항상 연산자 ID가 있으면 결과를 새 행에 인쇄해야합니다. 사용자가 활성 프로파일보다 많으면 운영자 ID와 이름 및 프로파일을 새 행에 출력해야합니다. 사용자가 비활성화 된 프로필 인 경우 데이터를 무시해야합니다. 예제에서 알 수 있듯이 처음부터 단위는 비활성화되어 있기 때문에 무시됩니다. 사용 가능한 satatus를 가진 사용자가 예제입니다. 출력 예제에서 볼 수 있듯이.

제 아이디어는 데이터를 배열로 가져 오지만 연산자 ID, 이름 및 프로필 만 출력하는 것입니다. 어떻게해야합니까? 당신은 TextReader를의 ReadLine 메서드를 호출하여 모든 라인을 읽을 수있는 TextReader를 가진

Console.WriteLine("Enter Input File Location: " + "\n"); 

      //Reads path specifed by the user for input. 
      string t = File.ReadAllText(Console.ReadLine()); 

      //Splits file where there is an equals sign. 
      t = t.Replace("=", ""); 
      //Removes all tabbed spaces. 
      t = t.Replace("\t", ""); 
      //Removes any new lines. 
      t = t.Replace("\n", ","); 
      //Removes blank spaces. 
      t = t.Replace(" ", ""); 
      //Removes the Underscore. 
      t = t.Replace("_", ""); 

      //Removes any leading or trailing whitespaces. 
      t = t.Trim(','); 

      //Writes formatted file to a pre defined ouput file's location. 
      File.WriteAllText(@"C:/3rd Quarter1.txt", t); 
+2

이 대구를 게시하시기 바랍니다 e 당신은 지금까지 썼다. 사람들은 일반적으로 코드를 작성하는 것을 좋아하지 않습니다. 그대로, 이것은 일의 묘사이지 질문이 아닙니다. –

+0

아무도 당신을 위해 일하지 않습니다. ** 특정 ** 프로그래밍 문제로 다시 시도해보십시오. 예 :'텍스트 파일에서 정보를 읽는 법'또는'이 텍스트 행을 구분 기호로 콜론을 사용하여 여러 부분으로 나누는 방법' – jgauffin

+0

여기 코드가 있습니다. 그것이 기본적으로 나뉘어지는 것은 등호를 제거하고 텍스트가 새로운 줄에서 시작되도록 형식을 지정합니다. 문제가있는 부분은 출력 할 정보를 선택적으로 선택하는 방법을 모르는 것입니다. heres waht 나는 지금까지 가지고있다 : 편집 된 quaeston을 보아라. – Paveetren

답변

0

:

이것은 내가 지금까지있는 것입니다.

당신은 잠시 (! textreader.EndOfFile) 특정 문자를 검색 할 수 있습니다 각 라인에 대한

에서이 작업을 수행 ->는 = 검색하고 그 뒤에 텍스트가 뭔가.

라인이 당신이 스트림에 전체 파일을로드하여 ..에 대한

시작을 찾고있는 물건을 찾기 위해 정규식을 사용할 수 있습니다 운영자 ID

-1

로 시작하는 경우도 확인할 수 있습니다. 다음과 같은 정규식을 사용하십시오 activeProfiles를 추출하기 위해 배열의 다른 정규식 체크를 할 필요가 다음 OFC,

@"Operator ID = (.+?) Name = (.+?) Active profile = (.+?) Enable status " 

모든 게시물을 발견 할 것이다 (그리고이 있는지 1 개 이상)

@"Active profile = (.+?) " 

해설자 .. 스트림 리더가 실제로 스트림에 넣는 것에 맞게 정규 표현식을 수정해야 할 수도 있습니다.여기에 프로그램이 같이 수있는 방법의 예는 다음과 같습니다 :

Here

은 reqex의

편집을 확인하는 좋은 도구입니다

static void Main(string[] args) 
    { 
     string path = @"c:\test.txt"; 
     string t = File.ReadAllText(path); 
     string pattern1 = @"OperatorID=(.+?),,Name=(.+?),(.+?),Enablestatus"; 
     Regex rgx = new Regex(pattern1); 

     //Removes all tabbed spaces. 
     t = t.Replace("\t", ""); 
     //Removes any new lines. 
     t = t.Replace("\n", ","); 
     //Removes blank spaces. 
     t = t.Replace(" ", ""); 
     //Removes the Underscore. 
     t = t.Replace("_", ""); 
     t = t.Replace("\r", ""); 

     MatchCollection matches = rgx.Matches(t); 
     List<string[]> test = new List<string[]>(); 
     foreach (var match in matches) 
     { 
      string[] newString = match.ToString().Split(new string[] { @"OperatorID=", @",,Name=", @",Activeprofile=", @",Enablestatus", }, StringSplitOptions.RemoveEmptyEntries); 

      for (int i = 3 ; i <= newString.Length; i++) 
      { 
       test.Add(new string[] { newString[0], newString[1], newString[i - 1] }); 
      } 

     } 

     foreach (var line in test) 
     { 
      Console.WriteLine("ID: {0}\nName: {1}\nActive Profile: {2}\n", line[0], line[1], line[2]); 
     } 

     Console.ReadKey(); 

이 상점에서 세부 사항에 관심을 많이 지불하지 않았나요 :)

편집 : 결과를 파일로 추가하려면 다음

 using (StreamWriter myWriter = new StreamWriter(@"c:\testOutput.txt")) 
    { 

     foreach (var line in test) 
     { 
      myWriter.WriteLine("ID: {0}", line[0]); 
      myWriter.WriteLine("Name: {0}", line[1]); 
      myWriter.WriteLine("Active Profile: {0}", line[2]); 
      myWriter.WriteLine(); 


     } 
    } 
+0

좋아,이 솔루션은 훌륭하게 작동한다 ..... 나는 한 가지 더 질문이있다. 필자는 콘솔에 새로운 텍스트 파일로 작성된 내용을 정확히 써야합니다. 다음 코드를 사용했지만 파일에 ID 만 씁니다. File.WriteAllLines (@ "C :/3rd Quarter1.txt", test [0]); 내가 도대체 ​​뭘 잘못하고있는 겁니까? WriteAllText 메서드를 시도했지만 buid 오류가 throw됩니다. – Paveetren

+0

왜 누군가가 이유를 밝히지 않고 답을 떨어 뜨릴 것입니다. 내 대답은이 일을하는 방법에 대한 최선의 아이디어입니다.이 커뮤니티는 함께 배우고, ppl을 배우는 것에 관한 것입니다. 그래서 저를 다운 그레이드하면 제발, 내가 실수로 배울 수있는 이유를 추가하십시오. – Tirdyr