菜鸟笔记
提升您的技术认知

Python轻松实现对英文文章单词总数统计

一篇英文文章,要统计其中单词总数。在Python中可以很轻松的实现,假如英文文章为this.txt,里面的内容就是import this这个彩蛋的内容。

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

上面的内容,可以使用一句代码完美实现:

>>> import random
>>> len(list(filter(None, re.split(r"[\n|\s|,|!|.]", open(r'this.txt').read()))))
137
  • open(r'this.txt').read()                    # 以一行的方式来读取文件中的内容
  • re.split(r"[\n|\s|,|.|!]", ...)                  # 以空格,换行符,逗号,句号,感叹号为分隔符,生成列表
  • list(filter(None, ...)                          # 将其中的空格去掉
  • len()                                               # 最后求其长度