bmd*_*cks 25
这是perl代码.计算单词可能有些主观,但我只是说它是任何不是空格的字符串.
open(FILE, "<file.txt") or die "Could not open file: $!";
my ($lines, $words, $chars) = (0,0,0);
while (<FILE>) {
$lines++;
$chars += length($_);
$words += scalar(split(/\s+/, $_));
}
print("lines=$lines words=$words chars=$chars\n");
Run Code Online (Sandbox Code Playgroud)
bmdhacks答案的变体可能会产生更好的结果是使用\ s +(甚至更好的\ W +)作为分隔符.考虑字符串"快速棕色狐狸"(如果不明显则增加空格).使用单个空格字符的分隔符将使字数为6而不是4.所以,试试:
open(FILE, "<file.txt") or die "Could not open file: $!";
my ($lines, $words, $chars) = (0,0,0);
while (<FILE>) {
$lines++;
$chars += length($_);
$words += scalar(split(/\W+/, $_));
}
print("lines=$lines words=$words chars=$chars\n");
Run Code Online (Sandbox Code Playgroud)
使用\ W +作为分隔符将停止标点符号(除其他外)作为单词计数.