Pythonで文字列内の引用符を数える方法について説明します。この記事は、Stack Overflowの質問「Pythonで引用符、疑問符、ピリオドを含む文を数える方法は?」と「Pythonで文字列中の引用符を見つける方法」を参考にしています。
引用符を含む文の数を数える
Pythonでは、引用符を含む文の数を数えるために、自作の関数を作成することができます。以下にその一例を示します。
def sentences_counter(text: str):
end_of_sentence = ".?!…"
sentences_count = 0
sentences = []
inside_a_quote = False
start_of_sentence = 0
last_end_of_sentence = -2
for i, char in enumerate(text):
if char == '\"':
inside_a_quote = not inside_a_quote
if not inside_a_quote and text[i-1] in end_of_sentence:
last_end_of_sentence = i
elif inside_a_quote:
continue
if char in end_of_sentence:
last_end_of_sentence = i
elif last_end_of_sentence == i-1:
sentences.append(text[start_of_sentence:i].strip())
sentences_count += 1
start_of_sentence = i
last_sentence = text[start_of_sentence:]
if last_sentence:
sentences.append(last_sentence.strip())
sentences_count += 1
return sentences_count, sentences
この関数は、引用符内の文を一つの文として数え、引用符外の文をそれぞれ別の文として数えます。
引用符の位置を見つける
Pythonでは、文字列内の引用符の位置を見つけるために、find
メソッドを使用することができます。以下にその一例を示します。
def find_quotes(temp):
start_pt = temp.find('\"')
end_pt = temp.find('\"', start_pt + 1)
quote = temp[start_pt + 1: end_pt]
return start_pt, end_pt, quote
この関数は、引用符の開始位置と終了位置を見つけ、その間の文字列を抽出します。
以上がPythonで引用符を数える方法と引用符の位置を見つける方法になります。これらの方法を活用して、Pythonでの文字列処理をより効率的に行うことができます。