如何在Python中计算句子中的单词?

我想将文本作为参数发送到python应用程序。应用程序将返回文本中的字数。下面是基本但有用的python应用程序示例。

null

Python脚本

我们有下面的python脚本 sentence_word_count.py . 它将句子作为参数,并根据空格将其拆分。使用 len() 函数以对给定列表中的元素进行计数。

import sys  def countwords(s):     count=len(s.split())     return count  print("Sentence:") print(sys.argv[1]) print("Total Word Count:") print(countwords(sys.argv[1]))
Python Script 
Python脚本

运行Python脚本

我们将使用 sentence_word_count.py 脚本以计数给定句子的字数。在这种情况下,句子是 This is a sample sentence .

$ python sentence_word_count.py "This is a sample sentence" Sentence: This is a sample sentence Total Word Count: 5

相关文章: PHP、Python、JavaScript、C/C++、C语言、BASH、java、PuxBeice编程语言中的函数和如何创建函数?

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享