Вот фрагмент, если это поможет:
Код: Выделить всё
def normalize_statement(statement):
# remove leading/trailing punctuation and excess whitespace
cleaned = statement.strip(whitespace + punctuation)
cleaned = re.sub(r'\s+', ' ', cleaned)
# capitalize first letter
cleaned = cleaned[0].upper() + cleaned[1:]
# ensure the statement ends with a period
if cleaned and not cleaned.endswith('.'):
cleaned += '.'
return cleaned
Я думал об использовании регулярного выражения для захвата всех подстрок, заключенных в одинарные или двойные кавычки, замените все кавычки подстроки захваченными группами, чтобы удалить кавычки , стандартизируйте оператор, а затем верните подстроки в кавычки на их исходные позиции. Вот обновленная функция:
Код: Выделить всё
def normalize_statement(statement):
# extract any and all substrings enclosed in quotation marks
quoted_pattern = re.compile(r'["\'](.*?)["\']')
quoted_substrings = quoted_pattern.findall(statement)
# replace the quoted substrings with the captured groups
cleaned = re.sub(quoted_pattern, lambda m: m.group(1), statement)
# remove leading/trailing punctuation and excess whitespace
cleaned = cleaned.strip(whitespace + punctuation)
cleaned = re.sub(r'\s+', ' ', cleaned)
# capitalize first letter for languages that use capitalization
cleaned = cleaned[0].upper() + cleaned[1:]
# ensure the statement ends with a period
if cleaned and not cleaned.endswith('.'):
cleaned += '.'
# replace quoted substrings (if any) back into their original positions after cleaning
for quoted_substring in quoted_substrings:
cleaned = re.sub(re.escape(quoted_substring.strip(whitespace + punctuation)), f'\"{quoted_substring}\"', cleaned, flags=re.IGNORECASE)
return cleaned
Я хочу, чтобы захватывался только текст между кавычками. — но как мне отличить апострофы от одинарных кавычек в моем шаблоне регулярного выражения? Я не слишком хорошо знаком с регулярными выражениями, поэтому, если у кого-то есть другой подход, я буду очень признателен!
Подробнее здесь: https://stackoverflow.com/questions/788 ... gle-quotat