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

问题描述 投票:0回答:13

我的任务是在第一个字母在字母范围内的句子中打印所有单词,例如: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 ascii string-comparison comparison-operators
13个回答
3
投票

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

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

0
投票

变量“单词”已包含短语的最后一个单词,但由于它不符合进入循环的条件,因此不会打印。所以你可以查看下面的解决方案。

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())

0
投票

这段代码适合我:

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

0
投票

我会使用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']

-1
投票
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())

2
投票

我将空间添加到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 = ''

1
投票

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

我之前犯了错误的使用单词>“g”,需要用“>”替换。此外,您需要添加最后一个打印命令,以便在短语没有以标点符号结尾的情况下打印最后一个单词(如给定示例中所示)

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 = ""
print(word)

1
投票

这就是我解决这个问题的方法。自从我成为一名初学者以来,这让我很难过。但似乎工作正常。

 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())

0
投票

只有一个关于练习的评论,作为编程练习,这种方法很好但你在实践中绝不会这样做。

您突出显示的两个问题是您正在比较整个单词而不是第一个单词。 只需更改:

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 = ""

0
投票

您声明不允许使用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字符。


0
投票

假设着名的引用只包含空格作为单词分隔符,这应该做的工作:

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

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

由于python具有此功能的历史记录,print()可以在很多方面使用。

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

print(" ".join(words))

你也可以用连接打印(被认为是丑陋的):

print(word+" ")

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

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

解释“{w}”并在出现“{w}”的地方用词替换它。

打印格式相当耗费CPU(但它仍然非常快)。通常任何打印操作都会减慢您的应用程序,如果您将来制作CPU密集型应用程序,则希望最小化输出(此处我不这样做,因为CPU不是主要关注点)。


0
投票

1. Split the words by building a placeholder variable: word

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

2. If character is alpha or (alphabet)

添加字符到字。检测到非alpha(空格,标点符号,数字......)定义单词的结尾并转到“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. Else

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

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

4. Or else

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

        else:
            word = ""

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

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


0
投票

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

这是我使用的代码。

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]
© www.soinside.com 2019 - 2024. All rights reserved.