编写一个Python程序,实现一个简单的文本压缩器。压缩规则是:将连续重复出现的字符替换为字符后跟一个数字,表示重复的次数。例如,"aaabbc" 应该被压缩为 "a3b2c1"
时间: 2024-11-09 19:27:51 浏览: 4
python字符串替换第一个字符串的方法
当然可以,下面是一个简单的Python程序,它使用了`itertools.groupby`函数来实现文本压缩:
```python
from itertools import groupby
def compress_text(text):
compressed = []
prev_char = None
count = 0
for char, group in groupby(text):
if prev_char is not None and char == prev_char:
count += 1
else:
compressed.append(f'{char}{count}' if count > 1 else char)
count = 1
prev_char = char
return ''.join(compressed)
# 示例
text = "aaabbc"
compressed_text = compress_text(text)
print(f"Original text: {text}")
print(f"Compressed text: {compressed_text}")
阅读全文