在Python中按索引替换字符串数据 [英] Index-wise Replacement of String Data in Python

查看:22
本文介绍了在Python中按索引替换字符串数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是个新手,刚开始从YouTube学习Python,我正在尝试做一个程序来替代 旧的二进制数转换成新的二进制数,并面临着数字替换的问题。想要以索引方式替换 我的文件(1x.txt)数据如下...

(01010110110111011110111101111011110101101101101011011011010101010101010101011101110101110111101)

这是一个随机数据,但它的形式是01,011,0111和01111。 我要将第010、第0110、第01110和第011110替换为第0000和第0000、第0110和第0000的结果 (0101 011011 011101111 0111101111 0111101 011011 01101 011011 01101 0101 0101 0101 01110111 010111 0111101) (01 0011 0001111 00001111 00001 0011 001 0011 001 01 01 01 000111 0111 00001) 到目前为止,我试着做一个程序,可以做这个任务,但它花了太多太多的时间,对于仅仅8MB的文件,它花费了超过2个小时 因此,任何人都可以向我推荐一种更好的方法来做同样的事情, 下面提到我的

def bytes_from_file(filename):
    newstring = ''

    old_list = ['010', '0110', '01110', '011110']
    new_list = ['0', '00', '000', '0000']

    with open(filename, "rb", buffering=200000) as f:
        while True:
            try:
                chunk = f.read()

            except:
                print('Error while file opening')
            if chunk:

                chunk2 = chunk.decode('utf-8')
                n = len(chunk2)

                i = 0
                while i < n:
                    flag = False
                    for j in range(6, 2, -1):

                        if chunk2[i:i + j] in old_list:
                            flag = True
                            index = old_list.index(chunk2[i:i + j])
                            newstring = newstring + new_list[index]

                            i = i + j

                            break
                    if flag == False:
                        newstring = newstring + chunk2[i]
                        i = i + 1
                        newstring=''.join((newstring))

            else:
                try:
                    f = open('2x.txt', "a")
                    f.write(newstring)
                    f.close()

                except:
                    print('Error While writing into file')

                break


bytes_from_file('1x.txt')

推荐答案

总的来说,您的操作过于复杂了,但最重要的问题在这里:

newstring = newstring + chunk2[i]
i = i + 1
newstring=''.join((newstring))

newstring已经是一个字符串,您可以通过重复串接子字符串(如newstring + chunk2[i])来构建它。这意味着''.join((newstring))字符串视为可迭代变量,并通过将其拆分成每个字母并执行联接操作将其联接起来。每次old_list与不匹配时,它都会执行,随着字符串变长,它会变得越来越慢。newstring=''.join((newstring))步骤实际上没有效果,但Python无法将其优化。另一方面,使用像newstring + chunk2[i]这样的技术来构建字符串,会破坏''.join可能具有的任何目的。

如果您的计划是构建单个字符串,您仍然希望使用''.join。但是您希望使用一次,并且希望对子字符串的列表使用它:

# initially, set
newstring = []
# any time you find something else to append to the output:
newstring.append(whatever)
# one time, right before opening the output file:
newstring = ''.join(newstring)

也就是说,还有其他方法。与构建列表不同,一种有用的技术是使用生成器yield需要编写的每个部分。然后,您可以迭代来编写这些字符串,或者在编写之前构建连接起来的字符串(如''.join(my_generator_function()))。或者,您可以打开这两个文件,并根据输入确定的每个输出块只打开.write

这篇关于在Python中按索引替换字符串数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆