给定一组包含汉字、基于拉丁字母的单词或两者混合的行,我想获得字数。
也就是说:
this is just an example
这只是个例子
最好给出 10 个单词;但当然,如果没有字典,示例最好被视为两个单独的字符。因此,此处 11 个单词/字符的计数也是可接受的结果。
显然,wc -w
不起作用。将6个汉字/5个单词视为1个“单词”,总共返回6个。
我该如何继续?我愿意尝试不同的语言,尽管 bash 和 python 目前对我来说最快。
最佳答案
您应该将文本拆分为 Unicode word boundaries ,然后计算包含字母或表意文字的元素。如果您使用 Python,则可以使用 uniseg或nltk例如,包。另一种方法是简单地使用 Unicode-aware regexes但这些只会在 simple word boundaries 上中断。另请参阅问题Split unicode string on word boundaries .
请注意,对于某些语言,您需要更复杂的基于字典的解决方案。 UAX #29 指出:
For Thai, Lao, Khmer, Myanmar, and other scripts that do not typically use spaces between words, a good implementation should not depend on the default word boundary specification. It should use a more sophisticated mechanism, as is also required for line breaking. Ideographic scripts such as Japanese and Chinese are even more complex. Where Hangul text is written without spaces, the same applies. However, in the absence of a more sophisticated mechanism, the rules specified in this annex supply a well-defined default.
关于utf-8 - 计算混合语言文档中的单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20215196/