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



我的任务是打印第一个字母在字母范围内的句子中的所有单词,例如: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()

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

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

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

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

我在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 = ''

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

我之前犯了使用单词>"g"的错误,需要用单词>"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)

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

您强调的两个问题是您正在比较整个单词而不仅仅是第一个字符。
只需更改:

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

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

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

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}",并在出现"{w}"的地方用单词替换它。

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

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

循环输入字符串中的每个字符 并检查字符是否为字母。然后在变量"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"。打印单词并设置"单词=空"字符串。

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"被显式编码为打印最后一个单词,如果它不以空格或标点符号等非字母字符结尾。

我做了这个完全相同的问题。大多数人遇到的问题(似乎没有人指出)是当你遇到双标点符号或标点符号后跟一个空格时。

这是我使用的代码。

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]

变量"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())

这段代码对我有用:

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

<</div> div class="one_answers">我会使用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']

这对我来说效果很好。我不得不添加最后两行代码,因为没有它们,它就不会打印最后一个单词,即使它以 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())
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())

最新更新