从文本文件中提取单词

时间:2008-11-09 22:05:11

标签: java text

假设您有一个像这样的文本文件: http://www.gutenberg.org/files/17921/17921-8.txt

有没有人有一个好的算法或开源代码从文本文件中提取单词? 如何获取所有单词,同时避免使用特殊字符,并保留“它是”等内容......

我在Java工作。 感谢

5 个答案:

答案 0 :(得分:17)

这听起来像是正则表达式的正确工作。这里有一些Java代码可以为您提供一个想法,以防您不知道如何开始:

String input = "Input text, with words, punctuation, etc. Well, it's rather short.";
Pattern p = Pattern.compile("[\\w']+");
Matcher m = p.matcher(input);

while ( m.find() ) {
    System.out.println(input.substring(m.start(), m.end()));
}

模式[\w']+多次匹配所有单词字符和撇号。示例字符串将逐字打印。请查看Java Pattern class documentation以了解详情。

答案 1 :(得分:3)

伪代码看起来像这样:

create words, a list of words, by splitting the input by whitespace
for every word, strip out whitespace and punctuation on the left and the right

python代码将是这样的:

words = input.split()
words = [word.strip(PUNCTUATION) for word in words]

,其中

PUNCTUATION = ",. \n\t\\\"'][#*:"

或您要删除的任何其他字符。

我相信Java在String类中具有相同的功能:String。split()。


在您在链接中提供的文字上运行此代码的输出:

>>> print words[:100]
['Project', "Gutenberg's", 'Manual', 'of', 'Surgery', 'by', 'Alexis', 
'Thomson', 'and', 'Alexander', 'Miles', 'This', 'eBook', 'is', 'for', 
'the', 'use', 'of', 'anyone', 'anywhere', 'at', 'no', 'cost', 'and', 
'with', 'almost', 'no', 'restrictions', 'whatsoever', 'You', 'may', 
'copy', 'it', 'give', 'it', 'away', 'or', 're-use', 'it', 'under', 
... etc etc.

答案 2 :(得分:3)

这是解决问题的好方法: 此函数接收文本作为输入,并返回给定文本中所有单词的数组

private ArrayList<String> get_Words(String SInput){

    StringBuilder stringBuffer = new StringBuilder(SInput);
    ArrayList<String> all_Words_List = new ArrayList<String>();

    String SWord = "";
    for(int i=0; i<stringBuffer.length(); i++){
        Character charAt = stringBuffer.charAt(i);
        if(Character.isAlphabetic(charAt) || Character.isDigit(charAt)){
            SWord = SWord + charAt;
        }
        else{
            if(!SWord.isEmpty()) all_Words_List.add(new String(SWord));
            SWord = "";
        }

    }

    return all_Words_List;

}

答案 3 :(得分:1)

基本上,你想匹配

([A-ZA-Z])+(“([A-ZA-Z])*)?

正确?

答案 4 :(得分:0)

您可以使用您制作的模式尝试正则表达式,并计算找到该模式的次数。

相关问题