regex - 如何使用正则表达式解决飞镖中的字数问题?
问题描述
做一个练习并试图得到所有的案例。
给定一个短语,计算该短语中每个单词的出现次数。
例如对于输入“olly olly in come free”
olly: 2
in: 1
come: 1
free: 1
到目前为止,我得到了什么:
Map<String, int> countWords(String words) {
var wordCount = Map<String, int>();
words.split(RegExp(r"\W")).forEach(
(word) {
wordCount.update(word.toLowerCase(), (value) => value + 1,
ifAbsent: () => 1);
},
);
return wordCount;}
所以它适用于简单的句子,但不适用于带有换行符、标点符号等的单词。
像这样的案例:
'one,\ntwo,\nthree'
'car: carpet as java: javascript!!&@\$%^&'
'Joe can\'t tell between \'large\' and large.'
'testing, 1, 2 testing'
'First: don\'t laugh. Then: don\'t cry.'
'Joe can\'t tell between app, apple and a.'
' multiple whitespaces'
',\n,one,\n ,two \n \'three\''
我不擅长正则表达式,所以我不确定我错过了什么。请帮我找到解决办法,谢谢。
解决方案
而不是使用每个非单词字符拆分字符串,只需获取单词:
var wordCount = {};
for (var match in RegExp(r"\w+('\w+)?").allMatches('my& string with with symbols&%!1')) {
wordCount.update(match.group(0).toLowerCase(), (value) => value + 1,
ifAbsent: () => 1);
}
print(wordCount);
推荐阅读
- python - Python:如何独立调整窗口大小和缓冲区大小?
- pivot-table - 如何在雪花中转置表格?我已经使用了 pivot 和 partition by 但仍然没有得到预期的输出
- html - 通过使菜单项刷新来改进 Bootstrap 平行四边形导航栏菜单
- c# - 在 AuthenticationParameters 和 AcquireToken 上出现错误
- python - contextvars:获取和设置原子
- python - Speed up Boto3 file transfer across buckets
- google-tag-manager - Google 跟踪代码管理器 - 计算延迟加载帖子的访问次数
- python-3.x - 从 Tensorflow_datasets 下载“Imdb_reviews”:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd5 in position 30 invalid continuation byte
- flutter - 在 stream.listen() 完成后 Flutter-Firebase 等待返回
- performance - 我想在空手道加特林中将一个 api 的结果用于另一个 api。两个 api 都在 gatling 中进行模拟