JAVA-如何忽略所有包含非字母的单词
我的程序使用Scanner读取txt文件,并使用Scanner.next()将其中的每个字逐字保存在ArrayList中。在这里,任何包含非字母的单词都应该被忽略,意思根本不应该算作单词(而不是替换它们)。例如:“U2”、“基于数据”或“hello!”根本不应计算在内 我可以阅读所有单词并将其保存到ArrayList,但我一直在忽略包含非字母元素的单词 这是我的部分代码:JAVA-如何忽略所有包含非字母的单词,java,Java,我的程序使用Scanner读取txt文件,并使用Scanner.next()将其中的每个字逐字保存在ArrayList中。在这里,任何包含非字母的单词都应该被忽略,意思根本不应该算作单词(而不是替换它们)。例如:“U2”、“基于数据”或“hello!”根本不应计算在内 我可以阅读所有单词并将其保存到ArrayList,但我一直在忽略包含非字母元素的单词 这是我的部分代码: public static void main(String[] args) { ArrayList<Word
public static void main(String[] args) {
ArrayList<Word> wordList = new ArrayList<Word>();
int wordCount = 0;
Scanner input;
try {
System.out.println("Enter the file name with extension: ");
input = new Scanner(System.in);
File file = new File(input.nextLine());
input.close();
input = new Scanner(file);
while(input.hasNext())
{
Word w = new Word(input.next().toLowerCase()); //should be case-insensitive
if(!wordList.contains(w)) //equals method overriden in Word class
wordList.add(w);
else
{
wordList.get(wordList.indexOf(w)).addCount();
}
wordCount++;
}
input.close();
publicstaticvoidmain(字符串[]args){
ArrayList wordList=新建ArrayList();
int字数=0;
扫描仪输入;
试一试{
System.out.println(“输入扩展名为:”)的文件名;
输入=新扫描仪(System.in);
File File=新文件(input.nextLine());
input.close();
输入=新扫描仪(文件);
while(input.hasNext())
{
Word w=新词(input.next().toLowerCase());//不区分大小写
if(!wordList.contains(w))//等于在Word类中重写的方法
添加(w);
其他的
{
get(wordList.indexOf(w)).addCount();
}
字数++;
}
input.close();
Word类是由我定义的,它只是一个简单的类,具有Word(String)和count(int)属性
我认为正则表达式是解决这个问题的方法,但由于我不知道如何在正则表达式中定义“非字母顺序”(我不知道正则表达式),我无法定义实数范围
非常感谢您的帮助!您可以使用regex
^[a-zA-Z]*$
只匹配字母表。在添加到数组列表之前使用此选项
现在,您可以使用String类的.matches()
检查它是否只包含字母。例如:
String str = "asd";
if (str.matches(^[a-zA-Z]*$)) {
// only alphabets
} else {
// something else
}
您可以使用此选项检查字符串是否仅包含字母。如果字符串仅包含字母,则返回true
;如果字符串包含其他字符,则返回false
Pattern.matches("[a-zA-Z]+", yourString)
你必须进口
import java.util.regex.Pattern;
我对java的模式东西tbh完全陌生。我不知道如何在代码中添加正则表达式,所以我只是尝试了Word w=new Word(input.next(“^[a-zA-Z]*$”).toLowerCase();但它出现了InputMismatchException..不,这不起作用。暂时存储字符串,然后在将其添加到列表之前检查它是否匹配。