others - python在字符串中,查找最长的单词

给定一个包含句子的字符串,我想找到该句子中最长的单词,然后返回该单词及它长度。

例如:string ="Hello i like cookies " . 我的程序应该返回"Cookies"和长度7.

字符串只包含字母和空格,单词用一个空格分隔。


def longestword(x):


 alist = []


 length = 0


 for letter in x:


 if letter !="":


 length += 1


 else:


 alist.append(length)


 length = 0


 return alist



时间:


current_max = 0


for v in values:


 if v>current_max:


 current_max = v



除了使用正规表达式,你可以简单地检查单词有没有字母,第一种方法是遍历列表并检测单词的开始或结束:


current_word = ''


current_longest = ''


for c in mystring:


 if c in string.ascii_letters:


 current_word += c


 else:


 if len(current_word)>len(current_longest):


 current_longest = current_word


 current_word = ''


else:


 if len(current_word)>len(current_longest):


 current_longest = current_word



最后一种方法是在生成器中拆分单词,并且找到它(在这个我使用了max函数):


def split_words(mystring):


 current = []


 for c in mystring:


 if c in string.ascii_letters:


 current.append(c)


 else:


 if current:


 yield ''.join(current)


max(split_words(mystring), key=len)



你可以尝试使用正规表达式:


import re



string ="Hello I like cookies"


word_pattern ="w+"



regex = re.compile(word_pattern)


words_found = regex.findall(string)



if words_found:


 longest_word = max(words_found, key=lambda word: len(word))


 print(longest_word)



只需搜索非空白字符组,然后按长度查找最大值:


longest = len(max(re.findall(r'S+',string), key = len))



这很简单:


def long_word(s):


 n = max(s.split())


 return(n)



在[48]中: long_word('a bb ccc dddd')

输出[48] :'dddd'

对于python 3,如果句子中两个词的长度相同,那么它将返回第一个出现的词。


def findMaximum(word):


 li=word.split()


 li=list(li)


 op=[]


 for i in li:


 op.append(len(i))


 l=op.index(max(op))


 print (li[l])


findMaximum(input("Enter your word:"))



正规表达式似乎是你最好的选择,首先使用re分割句子:


>>> import re


>>> string ="Hello I like cookies"


>>> string = re.findall(r'S+',string)



S+查找所有非空白字符并将它们放在列表中:


>>> string


['Hello', 'I', 'like', 'cookies']



现在你可以找到包含最长单词的列表元素的长度,然后使用列表推导来检索元素本身:


>>> maxlen = max(len(word) for word in string)


>>> maxlen


7


>>> [word for word in string if len(word) == maxlen]


['cookies']



此方法仅使用一个for循环,不使用String类中的方法,严格访问每个字符一次,


s ="Hello I like cookies"


word = ''


maxLen = 0


maxWord = ''


for c in s+' ':


 if c == ' ':


 if len(word) > maxLen:


 maxWord = word


 word = ''


 else:


 word += c



print"Longest word:", maxWord


print"Length:", len(maxWord)



我的建议,

import re


def longer_word(sentence):


 word_list = re.findall("w+", sentence)


 word_list.sort(cmp=lambda a,b: cmp(len(b),len(a)))


 longer_word = word_list[0]


 print"The longer word is '"+longer_word+"' with a size of", len(longer_word),"characters."


longer_word("Hello I like cookies")



...