下面是寻找句子中以a开头的单词的代码。"这是一棵苹果树。"
st = 'This is an apple tree'
for word in st.split():
if word[0]=='a':
print(word)
我想使它的功能,并采取在任何句子我想要的,如何到呢?这里是我想出的代码,但不是做我想要的。
def find_words(text):
for word in find_words.split():
if word[0]=='a':
print(word)
return find_words
find_words('This is an apple tree')
谢谢你。
你可以使用下面的代码。它将提供以'a'开头的单词的列表。
这是一个简单的if子句的列表理解。分割无参数默认情况下是用空格分割句子,而startwith方法有助于过滤'a'。
sentence = 'This is an apple tree'
words = [word for word in sentence.split() if word.startswith('a')]
问题在于你是如何定义for循环的。它应该是。
for word in text.split(' '):
...
就因为文本是你定义的函数中的参数
如果你想打印结果,可以试试这个。
st = 'This is an apple tree'
def find_words(text):
for word in text.split():
if word.startswith('a'):
print(word)
find_words(st)