【问题标题】:how to find and replace in python by indexing wise or in sequence wise如何通过索引或按顺序在python中查找和替换
【发布时间】:2021-05-26 00:40:26
【问题描述】:

我是软件新手,也是 python 新手,我有一个大文本文件 (data.txt),其中包含一个很长的字符串,内部文件数据应该像 = fghj123321fghjhgfj213fghh22131132132fghfgjhgf3123fhghfhfh313213hgh12hggj12313fjfhgjfhgf131gjgj1313fhfh 并想用excel文件(code.xlsx)中的给定代码替换,它包含data.txt中的替换代码 code.xlsx 在“A”列 fgh123j 和“B”列 xx012 中应该类似于这样,因此在数据文件 fgh123j 中用 xx012 替换。

为了更清楚起见,假设 data.txt 类似于 = 1231321233123312231233121231231231312222312131112312312123312333321321321321。并在 excel 文件(code.xlsx)中具有列“A”= 111、112、113、121、122、123、133、131、132、211...,以及列“B”=xx001、xx002, xx003 xx004, xx05, xx006, xx007, xx008, xx009, xx010 ....,所以如果我们使用随机查找和替换,它将首先更改所有 111,而不是 112,而不是 113,但它会弄乱整个文件。

所以我只想从 data.txt 中选择前三位(例如 123)并替换为 code.xlsx 中可用的替换代码(例如 xx006),而不是从 data.txt 中选择第二三位(例如例如 132)并使用 code.xlsx 中可用的替换代码(例如 xx009)进行更改,操作可以继续到字符串末尾。根据我的要求,

我很确定它可以用正则表达式完成,但没有知识。 我试过但它通过错误。

import os
import pandas as pd
import re
os.chdir('C:/New folder')

with open('data.txt', 'r') as f:
    string = f.read()

df4 = pd.read_excel("code.xlsx", header=None, index_col=False, dtype=str)
df4.columns = ['A', 'B', 'C']

for index, row in df4.iterrows():
    string = re.compile('.{1,3},', string)
    regex = re.compile(row['A'])
    read_file = regex.sub((row['C']), read_file)
    write_file = open('data.txt', 'w')
    write_file.write(read_file)

【问题讨论】:

  • 您能举例说明您需要实现的目标吗?举一个小输入数据、少量 excel 行和结果字符串的例子。
  • 想通过excel文件在文本文件中进行更改,但索引明智,如果我的文本文件中包含=1231321233123312231233121231231,并且excel文件中的代码在A列(1行)= 123,A列(2行)= 112,A列(3行)= 132,B列(1行)= xx01,B列(2行)= xx002,B列(3行)= xx003 ..所以当我开始替换操作时,它只选择前 3 位并替换代码,然后下 3 位并替换,在第一次替换后 = = =xx00113212331233122,在第二次替换后 = xx001xx00312331233122.它应该一直持续到文本文件结束 = xx001xx003xx.....

标签: python excel indexing regexp-replace


【解决方案1】:

这似乎是一种解决方案

import os
import pandas as pd

with open('data.txt', 'r') as f:
    string = f.read()

df4 = pd.read_excel("code.xlsx", header=None, index_col=False, dtype=str)
df4.columns = ['A', 'B']
m = dict()
for index, row in df4.iterrows():
    m[row['A']] = row['B']

out = ''
for i in range(0, len(string), 3):
    idx = string[i, i+3]
    try:
        out += m[idx]
    except IndexError:
        out += idx
   
with open('data_out.txt', 'w') as write_file
    write_file.write(out)

附:我没有测试这段代码——它只是一个草图

【讨论】:

  • 错误 [i, i+3], 预期类型 'Union[int, slice]', 改为 'Tuple[int, List[int]]'
  • 是的,这只是一小部分解决方案。应该修复一些错误。
猜你喜欢
  • 1970-01-01
  • 2015-05-24
  • 2016-09-06
  • 2020-08-20
  • 1970-01-01
  • 2017-03-31
  • 2016-03-27
  • 1970-01-01
  • 2023-04-09
相关资源
最近更新 更多