python实现更改文章单位并重新保存文章
**将txt文件中的数据进行单位转换,并将转换后的文章进行输出。 目前思路:将txt文件读到一个list里面,然后通过设定好的时间、长度、文件大小三个list,对比定位到文章中有单位的元素,再将前一位元素,即单位对应的数字进行大小变换。最后再将list输出为txt文件。
# 换算逻辑
def unitconversion(lengthUnit, lines, index, txt1, unit, s):
dindex = lengthUnit.index(D[unit])
lindex = lengthUnit.index(txt1)
if lines[index - 1][0] and lines[index - 1][-1] in '0123456789':
lines[index - 1] = str(float(lines[index - 1]) * (s ** (lindex - dindex)))
lines[index] = D[unit]
return lines
# 逻辑部分
def unit_translator(filename, D):
new_filename = filename[:-4] + '_translated.txt'
length = ['mm', 'cm', '0.1m', 'm', '10m', '100m', 'km']
filesize = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
time = ['sec', 'min', 'h']
numbersandalpha = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
with open(filename, 'r') as f:
st = f.readlines()
for stline in st:
lines = stline.strip().split(' ')
for index, txt1 in enumerate(lines):
if txt1[-1] not in numbersandalpha:
if txt1[:-1] in length and 'length' in D:
unitconversion(length, lines, index, txt1[:-1], 'length', 10)
if txt1[:-1] in time and 'time' in D:
unitconversion(time, lines, index, txt1[:-1], 'time', 60)
if txt1[:-1] in filesize and 'filesize' in D:
unitconversion(filesize, lines, index, txt1[:-1], 'filesize', 1024)
else:
if txt1 in length and 'length' in D:
unitconversion(length, lines, index, txt1, 'length', 10)
if txt1 in time and 'time' in D:
unitconversion(time, lines, index, txt1, 'time', 60)
if txt1 in filesize and 'filesize' in D:
unitconversion(filesize, lines, index, txt1, 'filesize', 1024)
st_translated = ' '.join([str(i) for i in lines])
with open(new_filename, 'a+') as f:
f.write(st_translated+'\n')
if __name__ == '__main__':
D = {'length': 'cm', 'filesize': 'GB'}
unit_translator('./Q2_example_text.txt', D)