过滤句子中以特定范围的字母开头的单词

新手上路,请多包涵

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

到目前为止,这是我的代码,但是它仍然打印以“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()

原文由 fortiswdg 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 597
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

原文由 cs95 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题