gpt4 book ai didi

Python - 减少文件大小的程序正在增加文件大小

转载 作者:太空宇宙 更新时间:2023-11-03 12:57:14 25 4
gpt4 key购买 nike

为了上大学,我正在研究压缩技术。我尝试进行的一项实验是用单个字符替换某些威尔士语字母(即二合字母)。

我认为用一个字符替换两个字符会减小文件大小(但略有减少),或者在最坏的情况下保持文件大小不变。我已经制作了一个 Python 脚本来执行此操作,但它实际上增加了文件大小。我对此进行测试的原始文件约为 74,400KB,输出程序约为 74,700KB。

这是我的 Python 代码:

replacements = {
'ch':'ƒ',
'Ch':'†',
'CH':'‡',
'dd':'Œ',
'Dd':'•',
'DD':'œ',
'ff':'¤',
'Ff':'¦',
'FF':'§',
'ng':'±',
'Ng':'µ',
'NG':'¶',
'll':'º',
'Ll':'¿',
'LL':'Æ',
'ph':'Ç',
'Ph':'Ð',
'PH':'×',
'rh':'Ø',
'Rh':'Þ',
'RH':'ß',
'th':'æ',
'Th':'ç',
'TH':'ð',
}
print("Input file location: ")
inLoc = input("> ")
print("Output file location: ")
outLoc = input("> ")

with open(inLoc, "r",encoding="Latin-1") as infile, open(outLoc, "w", encoding="utf-8") as outfile:
for line in infile:
for src, target in replacements.items():
line = line.replace(src, target)
outfile.write(line)

当我在一个只有几行长的非常小的文本文件上对其进行测试时,我查看了输出结果,它符合预期。

输入.txt:

Lle wyt ti heddiw?

Ddoe es i at gogledd Nghymru.

输出.txt:

¿e wyt ti heŒiw?

•oe es i at gogleŒ µhymru.

谁能解释一下发生了什么?

最佳答案

您正在更改文件的编码。 latin-1 总是每个字符 1 个字节,但 utf-8 不是,因此您的一些特殊字符被编码为多个字节,导致大小增加。

关于Python - 减少文件大小的程序正在增加文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36699062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com