Как сокращать фразы с помощью встроенных методов Polars?Python

Программы на Python
Ответить
Anonymous
 Как сокращать фразы с помощью встроенных методов Polars?

Сообщение Anonymous »

Мне нужно сократить серию или выражение фраз, извлекая слова с заглавной буквы и затем создавая сокращение на основе их пропорциональной длины.
Вот чего я пытаюсь достичь:
  • Извлекайте слова с заглавной буквы из каждой фразы.
  • Рассчитайте пропорциональную длину на основе общей длины слов с заглавной буквы в каждой фразе.
  • Отрегулируйте длину так, чтобы аббревиатура соответствовала целевой длине (например, 4 символа).
TODO: Если в результате аббревиатуры появляются дубликаты , мне нужно либо:
  • автоматически разрешить их (например, добавив цифры или изменив символы)
  • отметить их с предупреждением.
В настоящее время я использую функцию Python и сопоставляю ее с серией Polars.
Есть ли более эффективный способ сделать это с использованием встроенных методов Polars.
Вот мой текущий подход:
import polars as pl

def _abbreviate_phrase(phrase: str, length: int) -> str:
"""Abbreviate a single phrase by a constant length.

The function aims to abbreviate phrases into a constant length by focusing
on capitalized words and adjusting them according to their proportional lengths.

Example:
phrase = 'Commercial & Professional'
length = 4
res = _abbreviate_phrase(phrase, length)
print(res)
# CoPr
"""
# determine size of slices
capitalized_words = [word for word in phrase.split(' ') if word[0].isupper()]
word_lengths = [len(word) for word in capitalized_words]
total_word_length = sum(word_lengths)

if total_word_length == 0:
return '' # Return empty if no capitalized words

proportional_lengths = [round(wl / total_word_length * length) for wl in word_lengths]
total_proportional_length = sum(proportional_lengths)

# Adjust slices if their total length doesn't match target length
if total_proportional_length < length:
for i in range(length - total_proportional_length):
proportional_lengths += 1
elif total_proportional_length > length:
for i in range(total_proportional_length - length):
proportional_lengths -= 1

# Combine the abbreviated words and return the result
abbreviated_phrase = ''.join([word[:plength] for word, plength in zip(capitalized_words, proportional_lengths)])
return abbreviated_phrase

def abbreviate_phrases(phrases: pl.Series, length: int) -> pl.Series:
"""Abbreviate phrases by a constant length.

Example:
phrases = pl.Series([
'Sunshine',
'Sunset',
'Climate Change and Environmental Impact',
'Health and Wellness',
'Quantum Computing and Physics',
'Global Warming and Renewable Resources'
])
length = 4
res = abbreviate_phrases(phrases, length)
print(res)
# Series: '' [str]
# [
# "Suns"
# "Suns"
# "CEnI"
# "HeWe"
# "QCoP"
# "GWRR"
# ]
"""
abbreviates = phrases.map_elements(lambda x: _abbreviate_phrase(x, length), return_dtype=pl.String)
# if not abbreviates.is_unique().all():
# print('WARNING: There are duplicated abbreviations.')
return abbreviates

Изменить: сравнение производительности с решением Харбека
import timeit

def generate_phrases(n: int) -> pl.DataFrame:
# Repeat the original phrases 'n' times
phrases = pl.DataFrame({
"p": [
'Climate Change and Environmental Impact',
'Health and Wellness',
'Quantum Computing and Physics',
'Global Warming and Renewable Resources',
"no capital letters",
]
})
return pl.concat([phrases.with_columns(pl.col('p')+'_'+str(i)) for i in range(n)])

def compare_performance(n: int, length: int = 4):
phrases = generate_phrases(n)
abbreviate_phrases_time = timeit.timeit(lambda: abbreviate_phrases(phrases['p'], length), number=10)
abbreviate_phrases_harbeck_time = timeit.timeit(lambda: abbreviate_phrases_harbeck(phrases, phrase_column="p", length=length), number=10)
return abbreviate_phrases_time / abbreviate_phrases_harbeck_time

# Example usage
n = 200_000
performance_ratio = compare_performance(n=n, length=4)
print(f"Performance ratio ({n*5} rows): Original/Harbeck {performance_ratio:.2f}")
# Performance ratio (1000000 rows): Original/Harbeck 0.65


Подробнее здесь: https://stackoverflow.com/questions/791 ... in-methods
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»