首页 > 解决方案 > 在python中查找和替换大型文本文件(单行文件或单字符串文件)的最快方法

问题描述

每一个,我都面临在 python 中用大文本文件(它只是一个单行文件或单个字符串文件)缓慢查找和替换的问题,这需要很多时间来完成任务。我有一个excel文件,其中文本文件中的“A”列代码可用“B”列替换,但代码大约有一百万或更多要替换。您可以推荐的任何最快方式。提前致谢。我尝试了两种列出的方式

# first way

import pandas as pd
import re

df = pd.read_excel("rep-codes.xlsx", header=None, index_col=False, dtype=str)
df.columns = ['A', 'B']

for index, row in df.iterrows():
    open_file = open('final.txt', 'r')
    read_file = open_file.read()
    regex = re.compile((row['A']))
    read_file = regex.sub((row['B']), read_file)
    write_file = open('final.txt','w')
    write_file.write(read_file)


# 2nd way

df = pd.read_excel("rep-codes.xlsx", header=None, index_col=False, dtype=str)
df.columns = ['A', 'B']

fin = open("final.txt", "rt")
data = fin.read()

for index, row in df.iterrows():
    data = data.replace((row['A']), (row['B']))

fin.close()
fin = open("final.txt", "wt")
fin.write(data)
fin.close()

标签: pythonpandasdataframereplace

解决方案


如果.txt文件只是单列数据,那么操作应该就这么简单;

df = pd.read_excel("rep-codes.xlsx", header=None, index_col=False, dtype=str)
df.columns = ['A', 'B']

df['B'].to_csv('final.txt')

如果 .txt 文件是多列,您只需将 a 列的值与 b 列交换;

df = pd.read_excel("rep-codes.xlsx", header=None, index_col=False, dtype=str)
df.columns = ['A', 'B']

txt_df = pd.read_csv('final.txt')
txt_df['A']=df['B']
txt_df.to_csv('final.txt')

我还要猜测还有一些其他因素没有提到,比如不同的列大小等等。如果需要,让我知道还有什么需要更改的。


推荐阅读