使用python编程的字符串中最长的单词

时间:2017-06-20 10:27:01

标签: python-3.x

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

编写一个名为longest的函数,它将采用一串空格分隔的单词并返回最长的单词。 例如:

最长("这很棒")=> "绝佳" 最长的(" F")=> " F"

class Test(unittest.TestCase):
 def test_longest_word(self):
        sentence = "This is Fabulous"
        self.assertEqual('Fabulous', longest(sentence))

 def test_one_word(self):
        sentence = "This"
        self.assertEqual("This", longest(sentence))

到目前为止,这是我的解决方案;

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(len(word)> longest_size)                                 ^ SyntaxError:语法无效

任何帮助请我高度赞赏?

4 个答案:

答案 0 :(得分:1)

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']

See also, this question

答案 1 :(得分:0)

你错过了:在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) 

答案 2 :(得分:0)

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

第15行出现错误:print(longest_word(“ chair”,“ couch”,“ table”))

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

所以代码看起来像这样:

def 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("chair", "couch", "table")  
    word_list = words.split()  
    find_longest_word(word_list) 

答案 3 :(得分:0)

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