修复 python 中的基本字数统计

Fixing a basic word count in 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"

如果您想获取单词列表,则应改用 split 关键字。

>>> words = 'this is a test sentence'
>>> word_list = words.split()
>>> print(len(word_list))
5

问题是您将 "word" 作为一个包含 4 个字符的字符串进行迭代。

你的字数还有个问题,count words 和 count characters 的输出是一样的。

这是一个较短的固定代码:

word=raw_input("Enter your string please: ")
print ("Your word count:", len(word.split()))
print ("Your character count:", len(word))

输出:

Enter your string please: This is a Test
Your word count: 4
Your character count: 14
inp = raw_input("Enter your string: ")

word_count = len(inp.split())
chr_count = len(inp)

print(word_count, chr_count)

示例:

>>> Enter your string: foo bar
>>> 2 7

您正在遍历 "word" 的每个字母,这将导致长度为 4。您希望在修剪后在 space 上拆分输入字符串,然后获取结果的长度列表。

word=raw_input("Enter your string please: ")
print("Your word count: %s", len(word.strip().split(" ")))
print("Your character count: %s", (len(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

"word" 是可迭代的字符串对象,您正在遍历字符串 "word" 的每个符号,尝试将 "word" 更改为 word.split() 并通过len() 方法:

word = input("Enter your string please: ")
print("Your word count:", len(word.split()))
print("Your character count:", len(word))

您的 for 循环语句遍历字符串 "word" 而不是您保存为输入的变量词。 另外,您的 if 语句是针对单词的,而不是迭代器。

word=input("Enter your string please: ")
new_word = word.lstrip(" ").rstrip(" ")
new_word += ' '
count=0
for i in new_word:
    if i == " ":
        count += 1
print(count) 
print("Your word count: ", count)
print("Your character count: ", (len(new_word.rstrip(' '))))
print("Your character count: ", (len(word)))

您还可以从 collections 中的计数器中获取一些值。

from collections import Counter

my_string = "xxx yyy xxx"
c = Counter(my_string.split(' '))

print("number of words:", len(my_string.split(' ')))
print("number of characters:", len(my_string))
print("number of unique words:",len(c))
print("most common word:" , c.most_common()[0][0])
print("least common word:", c.most_common()[-1][0])

给出:

number of words 3
number of characters 11
number of unique words: 2
most common word: xxx
least common word: yyy