【问题标题】:Counting a string python计算一个字符串python
【发布时间】:2014-12-25 20:53:36
【问题描述】:

我对手动输入的字符串计数感到有点困惑。我基本上是在尝试计算单词数和不带空格的字符数。另外,如果可以的话,谁能帮忙数一下元音?

这就是我目前所拥有的:

vowels = [ 'a','e','i','o','u','A','E','I','O','U']
constants= ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']

s= input ('Enter a Sentence: ')

print ('Your sentence is:', s)

print ('Number of Characters', len(s));

print ('Number of Vowels', s);

【问题讨论】:

标签: python counting


【解决方案1】:
s = input("Enter a sentence: ")

word_count = len(s.split()) # count the words with split
char_count = len(s.replace(' ', '')) # count the chars having replaced spaces with ''
vowel_count = sum(1 for c in s if c.lower() in ['a','e','i','o','u']) # sum 1 for each vowel

更多信息:

str.splithttp://www.tutorialspoint.com/python/string_split.htm

sum

sum(sequence[, start]) -> value

Return the sum of a sequence of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0).  When the sequence is
empty, return start.

str.replace:http://www.tutorialspoint.com/python/string_replace.htm

【讨论】:

  • 非常感谢。这正是我所需要的。
  • 如果此解决方案解决了您的问题,请考虑将其作为官方答案(选票旁边的勾号)
【解决方案2】:
vowels = [ 'a','e','i','o','u']
sentence = "Our World is a better place"
count_vow = 0
count_con = 0
for x in sentence:
    if x.isalpha():
        if x.lower() in vowels:
            count_vow += 1
        else:
            count_con += 1
print count_vow,count_con

【讨论】:

  • 你在第8行有一个类型,应该是count_vow += 1
  • 啊抱歉是打字错误
【解决方案3】:

元音:

执行此操作的基本方法是使用 for 循环并检查每个字符是否存在于字符串、列表或其他序列(本例中为元音)中。我认为这是您应该首先学习的方式,因为它对初学者来说最容易理解。

def how_many_vowels(text):
  vowels = 'aeiou'
  vowel_count = 0
  for char in text:
    if char.lower() in vowels:
      vowel_count += 1
  return vowel_count 

一旦你了解更多并弄清楚list comprehensions,你就可以做到

def how_many_vowels(text):
  vowels = 'aeiou'
  vowels_in_text = [ch for ch in text if ch.lower() in vowels]
  return len(vowels_in_text)

或如@totem 所写,使用 sum

def how_many_vowels(text):
  vowels = 'aeiou'
  vowel_count = sum(1 for ch in text if ch.lower() in vowels)
  return vowel_count

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 2015-12-01
    • 2016-06-24
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    相关资源
    最近更新 更多