假设你有一个像这样的文本文件:
http://www.gutenberg.org/files/17921/17921-8.txt
请问是否有好的算法或开源代码,可以从文本文件中提取单词?如何获取所有单词,同时避免特殊字符,还保留像"it's"等内容?
我正在使用Java进行开发。 谢谢。
我正在使用Java进行开发。 谢谢。
这听起来像是需要使用正则表达式的工作。以下是一些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类文档以获取更多信息。
这是解决你问题的一个好方法: 该函数接收你输入的文本并返回给定文本中所有单词的数组。
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;
}
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
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.
基本上,你想要匹配
([A-Za-z])+('([A-Za-z])*)?
对吗?
Pattern.compile("[\\w']+");
- ScrollerBlasterPattern.compile("\\b[\\w']+\\b");
- TomalakPattern.compile("\\w[\\w-]+('\\w+)?")
将支持连字符和多个连字符的单词(例如sous-vide
,mise-en-scène
),同时支持撇号,但不在单词开头,并且必须跟随更多的字母(例如I've
,sous-vide'n
)。如果您想在撇号后允许更多字母(例如包括复数所有格),则可以使用Pattern.compile("\\w[\\w-]+('\\w*)?")
。 - pents90