python - 修复python中的基本字数
问题描述
所以我的代码有问题,我的字数总是等于“4”,每当我输入不同数量的字时,这都是不准确的。
这是我的代码:
word=raw_input("Enter your string please: ")
count=0
for i in "word":
count += 1
if word == " ":
print(count)
print "Your word count:", count
print "Your character count:", (len(word))
样本输出:
Enter your string please: ched hcdbe checbj
Your word count: 4
Your character count: 17
我的字符数非常好,这只是我的字数。我很困惑我需要解决什么。帮助将不胜感激!
解决方案
调试:
以下行无效,因为您正在迭代字符串 word 中的每个元素而不是用户输入:
for i in "word":
应该是:
for i in word:
完全修复(使用两个单独的变量进行单词和字符计数):
word= input("Enter your string please: ")
charCount = 0
wordCount = 0
for i in word:
charCount += 1
if i == ' ':
wordCount += 2
print("Your character count:", charCount)
print("Your word count:", wordCount)
现在,一种更短的方法:
使用str.format()
和len()
:
word = input("Enter your string please: ")
print("Total words: {}".format(len(word.split())))
print("Total Characters: {}".format(len(word)))
输出:
Enter your string please: hey, how're you?
Total words: 3
Total Characters: 16
推荐阅读
- python - 如何在 python 中访问库“plot_utils”?
- asp.net - IdentityServer3:错误请求 - 请求太长。请求头的大小太长,SignInMessage Cookie 重复
- c# - '进程无法访问文件'logs\dashboard.log',因为它正被另一个进程使用。' 在多任务环境中
- pyspark - 使用 pyspark 开发火花流但未获得预期结果
- apache-camel - 以编程方式获取 Apache Camel 组件操作、参数、选项说明
- php - PHP 如果状态为 OR 未按预期运行
- bitbucket - 如何使用 REST API 获取用户对 bitbucket 存储库的访问级别?
- c# - MVC - 缓存控制不适用于静态内容
- c# - 如何确保 API 一次只处理一个请求
- elasticsearch - 弹性搜索,过滤器无法使用 java.sql.Time 对象