在文本文件中查找唯一的单词

时间:2013-03-20 11:30:53

标签: java string

我正在用Java编写这个程序来查找文本文件中的唯一单词。我想知道这段代码是否正确,因为它甚至将空格显示为单词。

String[] words;
List<String> uniqueWords = new ArrayList<String>();
words = str1.split("[!-~]* ");
for (int i = 0; i < words.length; i++)
{
    if (!(uniqueWords.contains (words[i])))
    {
        uniqueWords.add(words[i]);
    }
}

例如,如果我的输入是“Hello world!世界怎么样?”我的输出数组/设置/列表应该有hello,world,how,is,

6 个答案:

答案 0 :(得分:5)

您可以使用Set找到唯一字词。 Set是一个不包含重复元素的Collection。

String[] words;
Set<String> uniqueWords = new HashSet<String>();
words = str1.split("[\\W]+");
for (int i = 0; i < words.length; i++)
{
    uniqueWords.add(words[i]);
}

答案 1 :(得分:4)

其他答案的略微修改版本(我喜欢简短而简单):

String[] words = str1.split("[!-~]* ");
Set<String> uniqueWords = new HashSet<String>();

for (String word : words) {
    uniqueWords.add(word);
}

注意:如果您要在!-~或空格上拆分,则应使用此选项:

String[] words = str1.split("[-!~\\s]+");

(短划线必须是第一个或最后一个)

答案 2 :(得分:2)

如果我们真的想要紧凑:

Set<String> unique = new HashSet<String>(Arrays.asList(str.toLowerCase().split("[-.,:;?!~\\s]+")));

答案 3 :(得分:1)

Set不允许重复,因为List允许重复。

String[] words;
Set<String> uniqueWords = new HashSet<String>();
words = str1.split("[!-~]* ");
for (int i = 0; i < words.length; i++)
    uniqueWords.add(words[i]); //Here you need not to check with set because it wont allow duplicates

答案 4 :(得分:0)

我建议您使用模式和匹配器,并将结果放入Set。

public void getWords()
{
    Set<String> words = new HashSet<String>();
    String pattern = "[a-zA-Z]+\\s";
    String match = "hello world how* are. you! world hello";
    Pattern compile = Pattern.compile(pattern);
    Matcher matcher = compile.matcher(match);
    while(matcher.find())
    {
        String group = matcher.group();
        boolean add = words.add(group);
        if(add)
        {
            System.out.println(group);
        }
    }
}

输出:

hello 
world 

通过更改模式来更改“单词”的定义。

答案 5 :(得分:0)

如果您想获得句子/任何类型文本中没有重复的单词,您可以试试这个:

   public static Map<String,Integer> getUniqueWords(String sentence){
   String[] word = sentence.split("[\\W]+");
        Map<String,Integer> uniqueWord = new HashMap<>();
        for (String e:word){
            if(!uniqueWord.containsKey(e)){
                uniqueWord.put(e,1);
            }else{
                uniqueWord.remove(e);
            }
        }
        return uniqueWord;
    }