提取字符串中的词语的java源码
时间: 2024-05-07 18:22:49 浏览: 8
以下是Java中提取字符串中的词语的示例代码:
```java
public class WordExtractor {
public static void main(String[] args) {
String text = "This is a sample text to extract words from.";
String[] words = text.split("[\\s.,;:!?(){}\\[\\]]+");
for (String word : words) {
System.out.println(word);
}
}
}
```
这个示例代码中,首先定义了一个字符串变量 `text`,它包含待提取词语的文本。然后,使用正则表达式 `"[\\s.,;:!?(){}\\[\\]]+"` 对文本进行分割,得到一个字符串数组 `words`,其中包含了所有的词语。最后,使用 `for` 循环遍历 `words` 数组,输出每个词语。
相关问题
提取中文字符串中的词语的java源码
下面是一个简单的 Java 实现,使用正则表达式和分词器来提取中文字符串中的词语:
```java
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.ansj.splitWord.analysis.ToAnalysis;
public class ChineseWordExtractor {
public static List<String> extract(String input) {
List<String> words = new ArrayList<>();
// 正则表达式匹配中文字符
Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]+");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
String match = matcher.group();
// 使用分词器分词
List<String> segmented = ToAnalysis.parse(match).getTerms();
words.addAll(segmented);
}
return words;
}
public static void main(String[] args) {
String input = "我爱北京天安门,天安门上太阳升。";
List<String> words = extract(input);
System.out.println(words);
}
}
```
上述代码中,首先使用正则表达式 `[\\u4e00-\\u9fa5]+` 匹配中文字符,然后使用分词器 `ToAnalysis` 对每个匹配到的字符串进行分词,最后将所有分词结果存储到列表中并返回。在 `main()` 方法中,我们演示了如何使用该方法提取中文字符串中的词语。
提取中文字符串中的词语,并统计出现的次数的java源码
以下是一个简单的Java程序,可以提取中文字符串中的词语,并统计它们出现的次数:
```java
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ChineseWordCount {
public static void main(String[] args) {
String str = "这是一个中文字符串,其中包含很多词语,比如说“中文”,“字符串”,“词语”,“统计”等等。";
Map<String, Integer> wordCount = countChineseWords(str);
System.out.println(wordCount);
}
public static Map<String, Integer> countChineseWords(String str) {
Map<String, Integer> wordCount = new HashMap<>();
Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]+");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
String word = matcher.group();
if (wordCount.containsKey(word)) {
wordCount.put(word, wordCount.get(word) + 1);
} else {
wordCount.put(word, 1);
}
}
return wordCount;
}
}
```
这个程序使用正则表达式来匹配中文字符(Unicode编码范围为`\u4e00-\u9fa5`),然后使用`Map`来统计每个词语出现的次数。在示例中,我们使用一个简单的字符串来演示这个程序。你可以将其替换为你想要统计的任何中文字符串。