Python 3.x 使用python编程的字符串中最长的单词

Python 3.x 使用python编程的字符串中最长的单词,python-3.x,Python 3.x,大家好,我仍然是python中的一员,我希望有人能帮我解决这个问题 编写一个名为longest的函数,它将接受一个空格分隔的字符串,并返回最长的一个。 例如: 最长(“这太棒了”)=>“太棒了” 最长(“F”)=>F 这是我目前的解决方案 def find_longest_word(word_list): longest_word = '' longest_size = 0 for word in word_list: if (len(word) &

大家好,我仍然是python中的一员,我希望有人能帮我解决这个问题

编写一个名为longest的函数,它将接受一个空格分隔的字符串,并返回最长的一个。 例如:

最长(“这太棒了”)=>“太棒了” 最长(“F”)=>F

这是我目前的解决方案

def find_longest_word(word_list):  
    longest_word = ''  
    longest_size = 0   
for word in word_list:    
    if (len(word) > longest_size)
    longest_word = word
    longest_size = len(word)      
return longest_word

words = input('Please enter a few words')  
word_list = words.split()  
find_longest_word(word_list) 
不幸的是,我在测试代码时遇到了这个错误 “文件”,第6行 if(长度(字)>最长尺寸) ^ SyntaxError:无效语法


我将非常感谢您的帮助。

您缺少if语句末尾的:号

使用下面更新的代码,我也修复了你的缩进问题

def find_longest_word(word_list):  
    longest_word = ''  
    longest_size = 0   
    for word in word_list:    
        if (len(word) > longest_size):
            longest_word = word
            longest_size = len(word)      
    return longest_word

 words = input('Please enter a few words')  
 word_list = words.split()  
 find_longest_word(word_list) 
编辑:如果你想要其中一个最长的单词,而不是所有的单词,上面的解决方案是有效的。例如,如果我的文本是“嘿!“你好吗?”它只会返回“嘿”。如果你想让它返回[“嘿”,“你好”,“是吗”,“你”] 最好用这个

def find_longest_word(myText):
  a = myText.split(' ')
  m = max(map(len,a))
  return [x for x in a if len(x) == m]

print (find_longest_word("Hey ! How are you ?"))  #['Hey', 'How', 'are', 'you']

代码示例不正确。如果尝试输出,我会收到以下消息:

第15行错误:打印(最长的单词(“椅子”、“沙发”、“桌子”))

TypeError:longest_word()接受1个位置参数,但给出了3个

代码如下所示:

def最长单词(单词列表):
最长单词=“”
最长尺寸=0
对于word\u列表中的word:
如果(len(word)>最长尺寸):
最长的单词
最长尺寸=长度(字)
返回最长的单词
单词=输入(“椅子”、“沙发”、“桌子”)
word\u list=words.split()
查找最长的单词(单词列表)

添加
在行的末尾
if(len(word)>longest_size)
并在hanks后缩进三行,但现在我在函数外部得到了“SyntaxError:'return”“这仍然是缩进错误吗?是的,有一个额外的空间。我修好了。请再试一次。我得到这个错误回溯:in-NameError:name'Fableus'没有定义删除“//Fableus”和“/['Hey'、'How'、'are'、'you']”我只是告诉你应该打印什么需要小心。拆分(“”),因为这不会拆分所有空格。例如,它不会拆分“James/nBlunt”。如果要拆分多行文本,最好将.split()保留为空。
def find_longest_word(myText):
  a = myText.split(' ')
  return max(a, key=len)


text = "This is Fabulous"
print (find_longest_word(text)) #Fabulous
def find_longest_word(myText):
  a = myText.split(' ')
  m = max(map(len,a))
  return [x for x in a if len(x) == m]

print (find_longest_word("Hey ! How are you ?"))  #['Hey', 'How', 'are', 'you']
# longest word in a text
text = input("Enter your text")
#Create a list of strings by splitting the original string
split_txt = text.split(" ")
# create a dictionary as word:len(word)
text_dic = {i:len(i)for i in split_txt}
long_word = max([v for v in text_dic.values()])
for k,v in text_dic.items():
    if long_word == v:
        print(k)