2012-01-05 4 views
0

단어가 파일에 나타나는 횟수를 계산하고 싶습니다. 이 작업을 수행하는 쉬운 방법이 있습니까? 파일이 직선 앞으로 텍스트 파일 인 경우는 C#에서 뿌리깊은 간단하다파일에서 단어가 몇 번 발견되는지 계산합니다.

+2

"숙제"태그가 있어야합니까? –

+2

어느 부분에서 문제가 있습니까? (1) 파일 읽기, (2) 단어로 파일 분할, (3) 단어의 출현 계산, (4) 결과 인쇄? –

+2

하지만 이미 쉬운 방법을 알고 있습니다 - stackoverflow ;-)에 문의하십시오 – necromancer

답변

2

...

private static int GetWordCount(string fileName, string word) 
{ 
    string content = File.ReadAllText(fileName); 
    string[] words = content.Split(new char[] {'.', '.', ' ', '?', '\n', '\r'}, 
        StringSplitOptions.RemoveEmptyEntries); 
    return words.Count(q => q == word); 
} 

이 방법은 문자열에 텍스트를 읽고 다음 몇 가지 구분 기호에 따라 문자열을 분할합니다. 그런 다음 LINQ 함수를 호출하여 개수를 얻고 다시 계산합니다.

+0

파일의 모든 단어 수를 계산하고 싶습니다. 솔루션을 제공해 주시겠습니까? – Tina

+0

그렇게하기는 쉽지만 실제로는 다른 질문입니다. 이 질문은 한 단어의 출현을 세는 것과 관련이 있습니다. 새로운 질문을 다른 질문에 대해 열어야하며, 이제는 상위 질문이이 질문을 닫은 것을 볼 수 있습니다. –

0
static void Main(string[] args) 
{ 
    StreamReader oReader; 
    if (File.Exists(@"C:\TextFile.txt")) 
    { 
      Console.WriteLine("Enter a word to search"); 
      string cSearforSomething = Console.ReadLine().Trim(); 
      oReader = new StreamReader(@"C:\TextFile.txt"); 
      string cColl = oReader.ReadToEnd(); 
      string cCriteria = @"\b"[email protected]"\b"; 
      System.Text.RegularExpressions.Regex oRegex = new System.Text.RegularExpressions.Regex(cCriteria,RegexOptions.IgnoreCase); 

      int count = oRegex.Matches(cColl).Count; 
      Console.WriteLine(count.ToString()); 
    } 

    Console.ReadLine(); 
} 

OR

다른 방법

. 이것은 당신이 더 잘 이해하는 데 도움이 될 수 있습니다.

컬렉션/제네릭 개념을 사용하여 우리는 쉽게 기준을 달성 할 수 있습니다. 아래 코드를 확인하고 자신의 풍경에 따라 업데이트하십시오.

1.) 처음 filestream 수입 IO 네임 스페이스를 사용하여 텍스트 파일(),

System.IO.StreamReader StreamReader1 = 
new System.IO.StreamReader(Server.MapPath("test.txt")); 

2) 캐릭터 라인 빌더에 추가를 참조하십시오.

StringBuilder sbData = new StringBuilder(); 
sbData.Append(StreamReader1.ReadToEnd()); 

3)는 StringBuilder (스페이스,은 마침표, 물음표, 느낌표, 아포스트로피, 뉴 라인)

string[] arrDataCollection = sbData.ToString().Split(' '); 

4) SortedList에 대한 사전 만들기에서 단어를 분할합니다.

SortedList<int, string> slData = new SortedList<int, string>(); 

5.) 유출 된 데이터를 반복하고 고유 한 모음을 가져옵니다.

for (int i = 0; i < Words.Length; i++) 
{ 
    slData.Add(i, arrDataCollection[i]); 
} 

6 ) 가져 별개의 단어를 계산 한 Hashtable에 보관하시기 바랍니다. 이 당신을 도울 것입니다 희망은 우리의 요구 사항에 따라

Hashtable htCollections = new Hashtable(); 
foreach (KeyValuePair<int, string> kvp in slData) 
{ 
    table.Add(kvp.Value, kvp.Key); 
} 

7) 마지막으로 Hashtable에서를 필터링 할 수 있습니다.

+0

대단히 고마워요. – Tina

+0

그러나 나는 아직도 생성 된 해시 테이블을 사용하는 방법을 모른다. – Tina

+0

내 문제를 정확히 설명하지 않을 수도 있습니다. 예를 들어 : string [] str = new string [] { "단어", "값", "단어", "값", "테스트", "단어"}; "단어", " 값 "과"테스트 ". – Tina

관련 문제