2017-11-23 9 views
0

私はPythonで問題を解決しています。 特定のテキストに含まれる単語の数が最も多い文章を検索したいと考えています。テキストは、文字、スペース、ドット(。)、疑問符(?)、および感嘆符(!)のN文字からなる文字列Sとして指定されます。 //テキストは、ドットで区切って文に分割できます。 !スペースで区切って文を単語に分割することができます。単語のない文は有効ですが、有効な単語は少なくとも1文字を含む必要があります。与えられたテキストコーディリティで最大の単語数を含む文を見つけよう

// S = "コーダーをテストします。試してみてください。"// S = "CVを忘れる...時間を節約するx x" // return 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 =であれば "私たち。KL" このコードは2を返して失敗しているが、それは1

が親切

+2

'string.strip () 'の後ろに余分なスペースを取り除いていることを確認してください。 – Jay

答えて

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 
0

することはできだけreplaceすべて?.文字で!文字、およびmaxタプル(ワード数、文)から2番目の要素を取得します:

def long_sentence(text): 
    return max([(len(sentence.strip().split()), sentence) for sentence in text.replace("?", ".").replace("!", ".").split(".")])[1] 
あなたが使用する必要があります
関連する問題