我想使用方法来计算句子中的单词数量.我写了这段代码,我不太清楚为什么它不起作用.无论我写什么,我只收到一个字数.如果你能告诉我如何解决我写的东西,而不是给我一个完全不同的想法,那将是伟大的:
import java.util.Scanner;
public class P5_7
{
public static int countWords(String str)
{
int count = 1;
for (int i=0;i<=str.length()-1;i++)
{
if (str.charAt(i) == ' ' && str.charAt(i+1)!=' ')
{
count++;
}
}
return count;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = in.next();
System.out.print("Your sentence has " + countWords(sentence) + " words.");
}
}
Run Code Online (Sandbox Code Playgroud) 我正在 Kaggle 新闻标题数据集上练习:https://www.kaggle.com/aaron7sun/stocknews#Combined_News_DJIA.csv
df = pd.read_csv('./data/Combined_News_DJIA.csv')
Run Code Online (Sandbox Code Playgroud)
当阅读新闻标题的 DataFrame 时,我得到了该系列的格式:
0 b"Georgia 'downs two Russian warplanes' as cou...
1 b'Why wont America & Nato help us? If they w...
2 b'Remember that adorable 9-year-old who sang a...
3 b' U.S. refuses Israel weapons to attack Iran:...
4 b'All the experts admit that we should legalis...
Run Code Online (Sandbox Code Playgroud)
我尝试使用以下内容:
df['Series'].str.decode("utf-8")
Run Code Online (Sandbox Code Playgroud)
然而输出是一个列表NaN。有任何想法吗?在整个 DataFrame 而不仅仅是一个 Series 上实现会很棒。