python - 如何在 Python 中查找并替换每行特定字符后面的文本?

标签 python regex csv case-insensitive

我有多个文件,其行如下所示,需要循环查找并替换“TEXT”,但仅在“=”之后

static.TEXT.here=change.TEXT.here

这是我当前的代码,但我只能在“=”之后指定,因为需要替换的“TEXT”在所有文件中的位置不一致

import re
src = open(r"sourcefile.txt").read()
dest = open(r"destinationfile.txt","w")
dest.write( re.sub(currentText,replacementText,src, flags=re.I) )
dest.close()

编辑

我采取了稍微不同的方法并导入了 csv 并使用“=”作为分隔符来创建单独的行,但现在很难整合我现有的 re.sub 代码来查找和替换文本,我正在使用的代码相关行:

import csv
with open("sourcefile.txt", 'rb') as csvfile:
csvreader = csv.reader(csvfile, delimiter= '=')
for row in csvreader:
    if len(row) >1:
        print row[1]

最佳答案

您可以遍历文件中的每一行并在 = 之后进行替换。例如:

formatted_contents = ''
for line in open(r"sourcefile.txt"):
    line_formatted = line.split('=')[-1].replace('TEXT', '**my_text**')
    formatted_contents += line_formatted

这假设每行中有一个=。如果每一行都没有,您可能需要添加一些您想要执行的操作的条件。

已更新

让我们一步一步地完成这个过程。

1。创建名为 sourcefile.txt 的文件,以便我可以测试该过程

$ cat sourcefile.txt 
static.TEXT.here=change.TEXT.here
more.static.TEXT.here=change.TEXT.here.more
even.more.static.TEXT.here=change.TEXT.here.even.more

2。浏览文件并打印每一行以练习在 python 中读取文件

>>> for line in open('sourcefile.txt'):
...     print line
... 
static.TEXT.here=change.TEXT.here

more.static.TEXT.here=change.TEXT.here.more

even.more.static.TEXT.here=change.TEXT.here.even.more

3。在 =

上拆分文件内容
>>> for line in open('sourcefile.txt'):
...     print line.split('=')
... 
['static.TEXT.here', 'change.TEXT.here\n']
['more.static.TEXT.here', 'change.TEXT.here.more\n']
['even.more.static.TEXT.here', 'change.TEXT.here.even.more\n']

4。我们想要获取 = 一侧的第二部分,因此我们将对其进行切片以执行 index[1]index[-1]

>>> for line in open('sourcefile.txt'):
...     print line.split('=')[-1]
... 
change.TEXT.here

change.TEXT.here.more

change.TEXT.here.even.more

5。将 TEXT 替换为 **MYTEXT**

>>> for line in open('sourcefile.txt'):
...     print line.split('=')[-1].replace('TEXT','**MYTEXT**')
... 
change.**MYTEXT**.here

change.**MYTEXT**.here.more

change.**MYTEXT**.here.even.more

6。现在我们有了 = 的正确后半部分,让我们将第一部分添加回

>>> for line in open('sourcefile.txt'):
...     print line.split('=')[0] + '=' + line.split('=')[-1].replace('TEXT','**MYTEXT**')
... 
static.TEXT.here=change.**MYTEXT**.here

more.static.TEXT.here=change.**MYTEXT**.here.more

even.more.static.TEXT.here=change.**MYTEXT**.here.even.more

7。最后,我们将其写入一个新文件

newfile=open('destinationfile.txt','w')
for line in open('sourcefile.txt'):
txt = line.split('=')[0] + '=' + line.split('=')[-1].replace('TEXT','**MYTEXT**')
    print txt
    newfile.write(txt)

8。确认它看起来正确

$ cat destinationfile.txt 
static.TEXT.here=change.**MYTEXT**.here
more.static.TEXT.here=change.**MYTEXT**.here.more
even.more.static.TEXT.here=change.**MYTEXT**.here.even.more

上面的内容是否可以简化并写得更好?当然。使用正则表达式可以用更少的步骤完成上述任务吗?是的。但我已经包含了上述步骤,希望能够引导您逐步完成该过程,了解 python 发生了什么。希望对您有所帮助。

关于python - 如何在 Python 中查找并替换每行特定字符后面的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41133370/

相关文章:

python - 正则表达式在python中的字符串中查找两个相同的字符串

unix - 如何从命令行合并两个CSV文件?

Python - 来自 CSV 文件的字典,每个键有多个值

python - 如何从数据框列中提取日期?

python - 无法识别凝聚聚类的新 distance_threshold 参数

python - 在 matplotlib 中用两个 y 轴格式化 x 轴标签(条形图和线图)

sql - ORACLE CONNECT BY LEVEL 产生重复行

python - Dict - 如果每个键有多个值,则提取最后一个元素

javascript - 使用 JavaScript 将指数 LaTeX 语法转换为 PHP 的 pow()

java - Guava 表到 CSV