从文本文件中提取单词

11
假设你有一个像这样的文本文件: http://www.gutenberg.org/files/17921/17921-8.txt 请问是否有好的算法或开源代码,可以从文本文件中提取单词?如何获取所有单词,同时避免特殊字符,还保留像"it's"等内容?
我正在使用Java进行开发。 谢谢。
5个回答

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类文档以获取更多信息。


1
我不得不稍微更改正则表达式,以便不包括数字、下划线,并且不包含以引号开头的单词,但除此之外,很好! - Nathan H
我必须如此转义 \w:Pattern.compile("[\\w']+"); - ScrollerBlaster
1
这有点偏题,但是你如何排除单引号在单词的开头或结尾? - ScrollerBlaster
1
@ScrollerBlaster,你可以使用单词边界来实现。Pattern.compile("\\b[\\w']+\\b"); - Tomalak
1
Pattern.compile("\\w[\\w-]+('\\w+)?") 将支持连字符和多个连字符的单词(例如sous-videmise-en-scène),同时支持撇号,但不在单词开头,并且必须跟随更多的字母(例如I'vesous-vide'n)。如果您想在撇号后允许更多字母(例如包括复数所有格),则可以使用 Pattern.compile("\\w[\\w-]+('\\w*)?") - pents90
它将数字识别为单词,我该如何去除它们?不识别“ I ”。 - Sreevisakh

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;

}

2
伪代码如下所示:
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.

这个代码相比正则表达式的优势在于它可以在一次简单的遍历中完成。 - Tom Leys
是的,Java有一个“split”方法,但它没有“strip”方法的等效物。 - Nathan H

1

基本上,你想要匹配

([A-Za-z])+('([A-Za-z])*)?

对吗?


0
您可以尝试使用正则表达式,使用您创建的模式,并运行计数器来统计该模式被找到的次数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接