あなたは一つの文端末句読点をカウントすると仮定すると、我々は、各文字列の文字をループや句読点をフィルタリングすることにより(文字カウント)ペアの辞書を生成することができます。中等初級レベルのデータ構造を持つ
デモここ
は、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の文を持っています。したがって、正規表現はより信頼性の高いアプローチです。
参照
あなたが彼らのために別々のカウントが必要ですか?句読点を数えたり、文章数を数えたりする目的は何ですか? "これは5つの文章ではないので!!!!!" –
「組み込み関数」とは何ですか?標準ライブラリモジュールを使用できますか? –
申し訳ありません。私は方法を意味した。例として、自動的に削除するものがあれば、変数sort.sort()を使用することが許可されていないソートの場合などは使用できません。 –