我正在尝试编写一个Java类,以便在文本文件中查找由()包围的单词,并在不同的行中输出单词及其出现的单词。
我怎么用Java写这段代码呢?
输入文件
School (AAA) to (AAA) 10/22/2011 ssss(ffs)
(ffs) 7368 House 8/22/2011(h76yu) come 789 (AAA)
Car (h76yu) to (h76yu) extract9998790
2/3/2015 (AAA) 输出文件
(AAA) 4
(ffs) 2
(h76yu) 3 这就是我到目前为止所得到的。
public class FindTextOccurances {
public static void main(String[] args) throws IOException {
int sum=0
String line = value.toString();
for (String word : line.split("(\\W+")) {
if (word.charAt(0) == '(‘ ) {
if (word.length() > 0) {
sum +=line.get();
}
context.write(new Text(word), new IntWritable(sum));
}
}
}发布于 2016-02-09 00:23:33
您可以在不拆分或使用如下正则表达式的情况下查找括号之间的文本(假设所有括号都是闭合的,并且您没有嵌套的括号):
int lastBracket = -1;
while (true) {
int start = line.indexOf('(', lastBracket + 1);
if (start == -1) {
break;
}
int end = line.indexOf(')', start + 1);
System.out.println(line.substring(start + 1, end - 1);
lastBracket = start;
}发布于 2016-02-09 00:20:43
如果你在"(\W+)“上拆分,你将保留所有不在括号之间的东西(因为你在括号中拆分单词)。
你想要的是一个匹配器:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
...
Map<String, Int> occurrences = new HashMap<>();
Matcher m = Pattern.compile("(\\W+)").matcher(myString);
while (m.find()) {
String matched = m.group();
String word =matched.substring(1, matched.length()-1); //remove parenthesis
occurrences.put(word, occurences.getOrDefault(word, 0)+1);
}发布于 2016-02-09 00:38:33
这可能会有帮助,我是用正则表达式做的,我没有声明变量,根据你的需要调整它们。我希望这能解决你的问题
BufferedReader fr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "ASCII"));
while(true)
{
String line = fr.readLine();
if(line==null)
break;
String[] words = line.split(" ");//those are your words
}
for(int i = 0;i<=words.length();i++)
{
String a = words[i];
if(a.matches("[(a-z)]+"))
{
j=i;
while(j<=words.length();)
{
count++;
}
System.out.println(a+" "+count);
}
}https://stackoverflow.com/questions/35274224
复制相似问题