【问题标题】:Words without Vowels [duplicate]没有元音的单词[重复]
【发布时间】:2021-03-20 19:23:21
【问题描述】:

在这段代码中,基本上我试图计算这句话中没有元音但有一些(或者可能是所有)我做错了的单词,这里是代码

par="zyz how are you"
count=0

for i in range(len(par)):
    if par[i]==" ":
        if par[i]!="a" or par[i]!="e" or par[i]!="i" or par[i]!="o" or par[i]!="u":
            count+=1
        
print("total words without vowel -> ",count)

【问题讨论】:

  • 这是一个基本的逻辑错误,您可以通过 a) 查看链接的副本来理解; b) 在维基百科或搜索引擎上查找“德摩根定律”;或 c) 通过手动仔细追踪逻辑来查看当 par[i] 是元音时会发生什么。
  • 但这仍然只计算非元音字符;您的代码关心 words 的唯一方法是,如果您的代码中有一些东西试图distinguish 单词。
  • 我想为您链接一个“如何将字符串拆分为单词?”的副本,但我能找到的每个人都在问一个更复杂的问题。

标签: python word sentence


【解决方案1】:

当您使用len(par) 时,它会返回字符串中有多少个字母。相反,您必须使用 par = "zyz how are you".split(" ")

逐字拆分字符串

拆分后,你会得到一个包含["zyz","how","are","you"]的列表

现在你可以只检查单词中是否有元音,而不是遍历每个字母

par = "zyz how are you".split(" ")
count = 0

for i in range(len(par)):
    if "a" in par[i] or "e" in par[i] or "i" in par[i] or "o" in par[i] or "u" in par[i]:
        pass
    else:
        count += 1

print("total words without vowel ->",count)

【讨论】:

  • par = "zyz 你好吗".split(" ") 哦!所以基本上在这个拆分函数中,它会在找到空间之前拆分每个字母?
  • 有点像用空格分割字符串,当然你也可以用它来分割许多其他字符。
【解决方案2】:

这是我为您编写的代码,可能不是最好的,但可以运行并带有注释,因此很容易理解!

par = "zyz how are you" # Define string variable with your sentence

def countwordsnowovels(string): # Define function that does it with argument called string
    count = 0 # Set the count to 0
    wordlist = string.split(" ") # Split the string into a list with every word as an entry
    for word in wordlist: # for every entry in the list "wordlist"
        if "a" not in word: # Check if there is no letter a in the word
            if "e" not in word: # Check if there is no letter e in the word
                if "i" not in word: # Check if there is no letter i in the word
                    if "o" not in word: # Check if there is no letter o in the word
                        if "u" not in word: # Check if there is no letter u in the word
                            count += 1 # If no wovels found, sum 1 to the count

        # Then for every word repeat this

    return count # After the scan (loop is complete) return the integer count to the function so we can process it later

count = countwordsnowovels(par) # Execute the function passing the argument par variable as string
print(count) # Now print the result

# Note that the count variable in the function is local only, so it will not "interfere" with the one outside the loop!

【讨论】:

  • 元音不是元音
猜你喜欢
  • 2021-09-07
  • 1970-01-01
  • 2021-10-10
  • 2019-12-23
  • 1970-01-01
  • 2021-03-24
  • 2016-10-08
  • 1970-01-01
  • 2013-08-12
相关资源
最近更新 更多