python实现更改文章单位(支持时间、长度、存储单位)

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)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值