找到包含给定文本代码中最大数量单词的句子

时间:2017-11-23 05:31:51

标签: python string

我在python中遇到问题解决问题。 您希望在某些给定文本中找到包含最多字数的句子。 text被指定为由N个字符组成的字符串S:字母,空格,点(。),问号(?)和感叹号(!) //文本可以通过将它分成点,?和!来分成句子。通过在空格处分裂,可以将句子分成单词。没有单词的句子是有效的,但有效单词必须至少包含一个字母。

// S ="我们测试编码员。试试看?"应该返回4。 // S ="忘记简历。 。省时间。 x x" //返回2

我的代码适用于测试用例和几乎很多极端情况。但是失败了。

我的代码

def findmaxwrds(S):
   list=[".","!","?"]
   c=0
   count = 0
   maxcount = 0
   if len(S)<1:
       return 0
   if len(S)==1:
       if S.find(".")!=-1 or S.find("?")!=-1 or S.find("!")!=-1:
           return 0
   for i in S:
       if i in list:
           c+=1
   if len(S)==c:
       return 0

   list1=S.split(" ")
   print list1
   for i in range(len(list1)):
     if list1[i]=="" or list1[i]=='.' or list1[i]=='?' or list1[i]=='!':
        continue
     else:
         count+=1
     if maxcount<count:
            maxcount=count

     if  list1[i].find(".")!=-1 or list1[i].find("?")!=-1 or list1[i].find("!")!=-1 :
         count=0

   return maxcount
print findmaxwrds(Str)

如果S =&#34;我们。 kl&#34; 此代码返回2失败,但应返回1.

请帮助

2 个答案:

答案 0 :(得分:0)

看起来像一个简单问题的复杂解决方案。只需遍历句子并计算单词数量。我就是这样做的。

import re #this is to import re module to delimit the main string s
s = 'as . rt'
list=[".","!","?"]
sentences = re.split('\\.|\\!|\\?',s) #sentences is now a list of all sentences
max_len_per_sentence = [len(sentence.strip().split(' ')) for sentence in sentences] 
#this will create a list with number of words per sentence
print(max(max_len_per_sentence)) #this will print max size element from the list

答案 1 :(得分:0)

您只需replace ?!个字符.个字符,然后从max元组中获取第二个元素(字数,句):

def long_sentence(text):
    return max([(len(sentence.strip().split()), sentence) for sentence in text.replace("?", ".").replace("!", ".").split(".")])[1]