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

python轻松实现对英文文章单词总数统计-ag真人游戏

一篇英文文章,要统计其中单词总数。在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()                                               # 最后求其长度
网站地图