python计算单词个数_如何在Python句子中计算单词数?

本文介绍了一个Python脚本,该脚本接收文本作为参数,通过拆分空格来计算句子中的单词数。示例代码展示了如何利用len()函数来统计列表元素,从而实现单词计数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python计算单词个数

python计算单词个数

I want to send my text to the python application as argument. The application will return the count of words in the text. Here is the basic but useful sample python application.

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

Python脚本 (Python Script)

We have following python script which is named sentence_word_count.py . It gets sentence as argument and split it according to spaces. Uses len() function in order to count elements in the given list.

我们有以下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 Script
Python脚本

运行Python脚本(Run Python Script)

We will use sentence_word_count.py script in order to count given sentence word count. In this case sentence is This is a sample sentence.

我们将使用sentence_word_count.py _单词_计数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
LEARN MORE  What Is A Function and How To Create Function In PHP, Python, JavaScript, C/C++, C#, Bash, Java , PowerShell Programming Languages?
了解更多信息什么是函数以及如何在PHP,Python,JavaScript,C / C ++,C#,Bash,Java和PowerShell编程语言中创建函数?

翻译自: https://www.poftut.com/count-words-sentence-python/

python计算单词个数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值