【问题标题】:Filter words in a sentence that begin with a certain range of letters过滤句子中以一定范围的字母开头的单词
【发布时间】:2017-07-05 02:09:22
【问题描述】:

我的任务是打印句子中首字母在一个字母范围内的所有单词,例如:h-z。

到目前为止,这是我的代码,但是它仍然打印以“g”开头的单词并且不打印最后一个单词。

famous_quote = input("Enter a one sentence quote: ").lower()
word = ""

for ltr in famous_quote:
    if ltr.isalpha() == True:
        word = word + ltr         
    else:
        if word > "g":
            print(word)
            word = ""
        else:
            word = ""

我只允许使用 ASCII 比较,我尝试比较 ASCII 值,但我不知道如何在这种情况下进行。

示例输入:

Wheresoever you go, go with all your heart

示例输出:

WHERESOEVER
YOU
WITH
YOUR
HEART

我想出的算法:

 - split the words by building a placeholder variable: word
 - Loop each character in the input string
 - check if character is a letter
 - add a letter to word each loop until a non-alpha char is encountered
 - if character is alpha  
 - add character to word    
 - non-alpha detected (space, punctuation, digit,...) defines the end of a     word and goes to else
 - else
 - check if word is greater than "g" alphabetically
 - print word
 - set word = empty string
 - or else
 - set word = empty string and build the next word
 - Hint: use .lower()

【问题讨论】:

    标签: python python-3.x string


    【解决方案1】:

    您可以定义一个简洁的小生成器来将您的句子分成单词并比较每个单词的第一个字母。

    def filter_words(sentence, lo, hi):
        lo, hi = map(str.upper, (lo, hi))
        words = sentence.upper().split()
    
        for word in words:
            if lo <= word[0] <= hi:
                yield word
    

    sentence = 'Wheresoever you go, go with all your heart'
    print(*filter_words(sentence, 'h', 'z'), sep='\n')
    
    WHERESOEVER
    YOU
    WITH
    YOUR
    HEART
    

    【讨论】:

      【解决方案2】:

      这就是我解决这个问题的方法。由于我是初学者,这让我很难过。但它似乎工作正常。

       quote = "quote goes here"
      
         word = ""
      
      for letter in quote:
              if letter.isalpha():
                  word += letter
      
              else:
                  if word > "":
                      print(word.upper())
                      word = ""
                  else:
                      word = ""
      
          print(word.upper())
      

      【讨论】:

        【解决方案3】:

        我在 user_input 中添加了空格,并且还使用了单词 > 'h'。下面是它的外观:

        user_input = input('Enter a phrase: ').lower()
        user_input += ' '
        word = ''
        for char in user_input:
            if char.isalpha():
                word += char
            else:
                if word > 'h':
                    print(word.upper())
                    word = ''
                else:
                    word = ''
        

        【讨论】:

          【解决方案4】:

          这段代码对我有用... 任务是:创建一个程序,输入一个短语(如一句名言)并打印所有以 h-z 开头的单词

          我之前错误地使用了 word > "g",需要将它替换为 word > "h"。 此外,您需要添加最后一个打印命令以打印最后一个单词,以防短语不以标点符号结尾(如给定示例中)

          phrase = input ("Please enter a phrase: ").lower()
          word = ""
          for letter in phrase:
              if letter.isalpha():
                  word += letter
              else:
                  if(word > "h" ):
                      print(word)
                      word = ""
                  else:
                      word = ""
          if word.lower() > 'h':    
              print(word)
          

          【讨论】:

          • 您能否解释一些代码以使答案对未来的读者有用? From Review
          • 您好,为了更清楚,我添加了一些解释。谢谢!
          【解决方案5】:

          对练习只有一条评论,作为编程练习,这种方法很好,但在实践中你永远不会这样做。

          您强调的两个问题是您正在比较整个单词,而不仅仅是第一个字符。
          简单地改变:

          if word > "g":
          

          收件人:

          if word and word[0] > "g":
          

          如果引用没有以标点符号结尾,您将错过最后一个单词,只需在循环后添加:

          if word:
               print(word)
          

          你可能注意到输出都是大写的,所以.lower()整个引用可能是一个问题,或者你可以只是.lower()比较,例如:

          famous_quote = input("Enter a one sentence quote: ")
          ...
              if word and word[0].lower() > "g":
          

          注意:您可以简化else: 条件:

          else:
              if word and word[0] > "g":
                  print(word)
              word = ""
          

          【讨论】:

          • 如果我使用 if word[0] > "g" 我得到 IndexError: string index out of range
          • 您可能需要先检查是否有 word,对于连续有 2 个标点符号的情况,例如'. '。已更新。
          【解决方案6】:

          您声明不允许使用split() 方法。我不确定你可以使用什么,所以这里有一个解决方案(不是最佳解决方案)。

          famous_quote = input("Enter a one sentence quote:") + ' '
          current_word = None
          for c in famous_quote:
            if ('a' <= c <= 'z') or ('A' <= c <= 'Z'):
              if current_word is None:
                current_word = c        # start a new word
              else:
                current_word += c       # append a new letter to current word
            else:
              if current_word is not None:
                f = current_word[0]     # first letter
                if ('h' <= f <= 'z') or ('H' <= f <= 'Z'):
                  print(current_word)
              current_word = None
          

          这是该程序的示例运行。它保留小写和大写。它还会在任何非 ASCII 字符上拆分单词。

          Enter a one sentence quote: Whereever you go, there you are!!!
          Whereever
          you
          there
          you
          

          注意:由于在遇到非 ASCII 字符时进行打印,所以在 famous_quote 的末尾附加了一个非 ASCII 字符。

          【讨论】:

            【解决方案7】:

            假设名言只包含空格作为单词分隔符,这应该可以完成工作:

            words = input("Enter a one sentence quote: ").lower().split()
            for word in words:
             if word[0] > 'g':
              print("{w} ".format(w = word))
            

            split() 将字符串转换为列表(数组)。默认情况下,它以空格字符作为参数(因此我没有给出参数)并返回单词列表。

            print() 可以在很多方面使用,因为 python 有这个函数的历史。

            你可以 .join() 列表(得到一个字符串作为结果)并打印它:

            print(" ".join(words))
            

            您还可以使用连接进行打印(被认为是丑陋的):

            print(word+" ")
            

            或者您可以使用格式化打印,我经常使用它来提高可读性:

            print("{w} ".format(w = word))
            

            解释“{w}”并将其替换为 word 出现在“{w}”的任何位置。

            打印格式化相当消耗 CPU(但它仍然非常快)。通常任何打印操作都会减慢您的应用程序,如果您将来制作 CPU 密集型应用程序,您希望尽量减少输出(这里我不这样做,因为 CPU 不是主要问题)。

            【讨论】:

            • 这与我的回答有何不同?
            • @Coldspeed: man diff :-D joking 我们刚刚同时发布。您的解决方案在 CPU 上性能更高,这就是我赞成它的原因。不过我喜欢我的格式 :-) 一个 CPU 杀手哈哈
            • 相差 6 分钟。 ;/
            • 人的一生中 6 分钟内会发生很多事情 :-)
            • 感谢您的解决方案。但是,我是编程新手,我不知道您在最后一行代码中做了什么。你能解释一下吗?我非常想知道。另外,你能用简单的语言告诉我 split() 函数的作用吗?
            【解决方案8】:

            1。通过构建占位符变量来拆分单词:word

            循环输入字符串中的每个字符 并检查字符是否为字母。然后将字母添加到变量“word”中。循环直到遇到非字母字符。

            2。如果字符是字母或(字母)

            在单词中添加字符。 检测到的非字母(空格、标点符号、数字……)定义了单词的结尾并转到“else”部分。

            input_quote = input("Enter a 1 sentence quote, non - alpha seperate words: ")
            word = ""
            
            for character in input_quote:
                if character.isalpha():
                    word += character
            

            3。否则

            按字母顺序检查单词是否大于“g”。打印 word 并设置 "word = empty" 字符串。

                else:
                    if word and word[0].lower() >= "h":
                        print("\n", word.upper())
                        word = ""
            

            4。否则

            设置 word = 空字符串并构建下一个单词。

                    else:
                        word = ""
            
            if word.lower() >= "h":
                print("\n", word.upper())
            

            最后一个“if”被显式编码以打印最后一个单词,如果它不以空格或标点符号等非字母字符结尾。

            【讨论】:

            • 一些关于这段代码的内容以及它的作用会很有用。
            【解决方案9】:

            我做了同样的问题。大多数人遇到的问题(似乎没有人指出)是当您遇到双标点符号或标点符号后跟空格时。

            这是我使用的代码。

            phrase = input("Please enter a famous quote: ")
            word = ""
            
            for letter in phrase:
                if letter.isalpha() is True:
                    word += letter
            
                elif len(word) < 1: <--- [This is what accounts for double punctuations]
                word = ""
            
                elif word[0].lower() >= "g":
                        print(word)
                        word = ""
            
                else:
                    word = ""
            print(word) <--- [accounts for last word if not punctuated]
            

            【讨论】:

              【解决方案10】:

              变量“word”已经包含了你的最后一个词,但由于它不满足进入循环的条件,它不会被打印出来。因此,您可以检查以下解决方案。

              phrase = input("Enter a phrase after this: ")
              word = ""
              for char in phrase:
                    if char.isalpha():
                          word += char
                    else:
                          if word != "":
                                if word[0].lower() >= "h":
                                      print(word.upper())
                                      word = ""
                                else:
                                      word = ""
              if word[0].lower() >= "h":
                    print(word.upper())
              

              【讨论】:

                【解决方案11】:

                此代码适用于我:

                phrase=input("Enter a one sentence quote,non-alpha separate words: ")
                word=""
                
                for character in phrase:
                    if character.isalpha():
                       word+=character
                   else:
                       if word.lower()>="h".lower():
                            print(word.upper())
                            word=""                  -----this code defines the end of a word 
                
                       else:
                            word=""
                
                
                print(word.upper())              ------this will print the last word
                

                【讨论】:

                • 根据其他答案,您的答案似乎没有解决问题的范围。但是,为了使您的答案更易于阅读和更快地参考,建议您将代码示例发布为具有代码格式的文本,而不是存储在外部站点上的屏幕截图。
                • 您好,谢谢您的建议,但我的回答不是截图。我以代码格式编写了它,这段代码解决了这个问题。我正在上相同的在线课程,并且得到了我想要的结果。
                【解决方案12】:

                我会使用regular expressionslist compreshension,如下面的函数所示。

                def words_fromH2Z():
                    text = input('Enter a quote you love : ')
                    return [word for word in re.findall('\w+', text) if not word[0] in list('aAbBcCdDeEfFgG')] 
                

                当我通过输入“我总是访问堆栈溢出寻求帮助”来测试函数时,我得到:

                words_fromH2Z()
                
                Enter a quote you love : I always Visit stack Overflow for Help 
                
                ['I', 'Visit', 'stack', 'Overflow', 'Help']
                

                【讨论】:

                  【解决方案13】:

                  这对我来说效果很好。我必须添加最后两行代码,因为没有它们,它不会打印最后一个单词,即使它以 h 和 z 之间的字母开头。

                  word = ""
                  quote = input("Enter your quote")
                  for char in quote:
                      if char.isalpha():
                          word += char
                      elif word[0:1].lower() > "g":
                              print(word.upper())
                              word = ""
                      else:
                          word = ""
                  if word[0:1].lower() > "g":
                              print(word.upper())
                  

                  【讨论】:

                    【解决方案14】:
                    famous_quote = input("Enter a one sentence quote:")
                    current_word = None
                    
                    for c in famous_quote:
                        if c.isalpha():
                            if (c >= 'a') or (c >= 'A'):
                                if current_word is None:
                                    current_word = c
                                else:
                                    current_word += c
                        else:
                            if current_word is not None:
                                f = current_word[0]
                                if ('h' <= f <= 'z') or ('H' <= f <= 'Z'):
                                    print (current_word.upper())  
                            current_word = None
                    if famous_quote[-1].isalpha():
                        print (current_word.upper())
                    

                    【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 2014-03-14
                    • 1970-01-01
                    • 1970-01-01
                    • 2020-10-31
                    • 2015-07-14
                    • 1970-01-01
                    • 2020-01-29
                    相关资源
                    最近更新 更多