2017-10-21 6 views
-3

「終了文」を数えたいと思います。フルストップ、感嘆符、および疑問符が含まれています。文章中の句読点を数える良い方法はありますか?

私はこれを行うために少しループを書いていますが、よりよい方法があるかどうか疑問に思っていました。組み込み関数は使用できません。

for line in textContent: 
    numberOfFullStops += line.count(".") 
    numberOfQuestionMarks += line.count("?") 
    numberOfQuestionMarks += line.count("!") 

numberOfSentences = numberOfFullStops + numberOfQuestionMarks + numberOfExclamationMarks 
+0

あなたが彼らのために別々のカウントが必要ですか?句読点を数えたり、文章数を数えたりする目的は何ですか? "これは5つの文章ではないので!!!!!" –

+0

「組み込み関数」とは何ですか?標準ライブラリモジュールを使用できますか? –

+0

申し訳ありません。私は方法を意味した。例として、自動的に削除するものがあれば、変数sort.sort()を使用することが許可されていないソートの場合などは使用できません。 –

答えて

0

あなたは一つの文端末句読点をカウントすると仮定すると、我々は、各文字列の文字をループや句読点をフィルタリングすることにより(文字カウント)ペアの辞書を生成することができます。中等初級レベルのデータ構造を持つ

デモここ

は、3つのオプションが提示されているトップダウン:

import collections as ct 


sentence = "Here is a sentence, and it has some exclamations!!" 
terminals = ".?!" 

# Option 1 - Counter and Dictionary Comprehension 
cd = {c:val for c, val in ct.Counter(sentence).items() if c in terminals} 
cd 
# Out: {'!': 2} 


# Option 2 - Default Dictionary 
dd = ct.defaultdict(int) 
for c in sentence: 
    if c in terminals: 
     dd[c] += 1 
dd 
# Out: defaultdict(int, {'!': 2}) 


# Option 3 - Regular Dictionary 
d = {} 
for c in sentence: 
    if c in terminals: 
     if c not in d: 
      d[c] = 0 
     d[c] += 1 
d 
# Out: {'!': 2} 

は1周り、別々のsentencesのリストについては、さらにループを拡張するには後者のオプションの

for sentence in sentences: 
    # add option here 

注:dict.values()総文あたりの総句読点、例えばを合計しますsum(cd.values())


更新、あなたはターミナルpunctutationによって文を分割したいと仮定すると、正規表現を使用します。

import re 


line = "Here is a string of sentences. How do we split them up? Try regular expressions!!!" 


# Option - Regular Expression and List Comprehension 
pattern = r"[.?!]" 
sentences = [sentence for sentence in re.split(pattern, line) if sentence] 
sentences 
# Out: ['Here is a string of sentences', ' How do we split them up', ' Try regular expressions'] 

len(sentences) 
# Out: 3 

お知らせlineは5つの端子が、唯一の3の文を持っています。したがって、正規表現はより信頼性の高いアプローチです。

参照

+0

ありがとうございます。 :-)大きな助け。 –

+0

問題ありません。私はあなたのコメントに基づいて投稿を更新しました。うまくいけばあなたが探しているものに近いでしょう。また、回答が投稿され続けるので、あなたが助けてくれたものをupvoteし、最終的な解決策を受け入れることを忘れないでください。 – pylang

関連する問題