【发布时间】:2014-05-10 07:11:46
【问题描述】:
我正在尝试编写一个程序,从文本文件中读取单词并将其唯一地插入到数组中,同时为每个单词保留单独的计数。此外,我需要去掉标点符号并将所有字母移动到小写。
任何人都可以帮助它,将不胜感激。
import java.util.Scanner;
import java.io.*;
public class text {
public static void main (String [] args){
try
{
String currentWord,normalizedWord;
String word [] = new String [1000];
int freq [] = new int [1000];
int wCnt = 0;
int loc;
Scanner kb = new Scanner(System.in);
//get the name of the file
System.out.print("Enter the name of a file:");
String filename = kb.nextLine();
//Open file
File file = new File(filename);
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext()){
currentWord = inputFile.next();
normalizedWord = normalize(currentWord);
System.out.println("The normalized word is: " + normalizedWord);
loc = search(word,wCnt,normalizedWord);
print(word,wCnt);
if(loc == -1){
insertUnique(word, freq, wCnt, normalizedWord);
freq[loc]++;
wCnt++;
}
else
freq[loc]++;
}
}
catch (FileNotFoundException e){
System.out.println(e.getMessage());
System.exit(0);
}
}
public static void print(String[] word, int wCnt) {
System.out.print("{ ");
for (int i=0; i < wCnt; i++)
System.out.print(word[i] + " , ");
System.out.print("}");
}
public static int search(String[] word, int wCnt, String normalizedWord) {
for (int i = 0; i < wCnt; i++){
if (word[i]==normalizedWord)
return i;
}
return -1;
}
public static int insertUnique(String[] word, int[] freq, int wCnt,
String normalizedWord) {
if(!isIn(word,wCnt,normalizedWord)){
word[wCnt] = normalizedWord;
wCnt++;
}
return wCnt;
}
public static boolean isIn(String[] word, int wCnt, String normalizedWord) {
for (int i = 0; i < wCnt; i++){
if(word[i]== normalizedWord)
return true;
}
return false;
}
public static String normalize(String wrd) {
if (wrd.charAt(0) == '"' )
wrd = wrd.substring(1);
int wrdLength = wrd.length();
//To remove all punctuation
if (wrd.charAt(wrdLength-1) == '"')
wrd = wrd.substring(0,wrdLength -1);
//To remove all punctuation
if (wrd.charAt(wrdLength-1) == '?')
wrd = wrd.substring(0,wrdLength -1);
return wrd;
}
}
【问题讨论】:
-
您到底有什么问题?到目前为止,您的问题是“为我编写代码”。
-
我正在尝试删除标点符号并将所有大写变为小写
-
我正在尝试编写一个程序,从文本文件中读取单词并将唯一插入到数组中,同时为每个单词保留单独的计数。我还需要去掉标点符号并将所有字母都变成小写
-
那么,你的问题是什么?
-
为什么不使用
HashMap<String, Integer>,以您的单词为键,以您的计数为值。
标签: java string normalization