繁体   English   中英

如何在文本文件中查找和替换模式“);”?

[英]How to find and replace the pattern “);” in a text file?

我有一个包含特殊字符的文本文件。 我要替换");" "firstdata);seconddata" 问题是")"";" 应该在一起,然后替换为"firstdata);seconddata"

我有以下代码。

import re
string = open('trial.txt').read()
new_str = re.sub('[);]', 'firstdata);seconddata', string)
open('b.txt', 'w').write(new_str)

请为我建议如何更改代码以获得正确的输出。

您可以在Python中使用内置的str.replace()方法

string = "foobar);"
string.replace(");", 'firstdata);seconddata')  # -> 'foobarfirstdata);seconddata'

这是Python中常见字符串操作的文档https://docs.python.org/3/library/string.html

应该这样做:

import re

with open("file.txt", "r") as rfile:
    s = rfile.read()
    rplce = re.sub('\);', "REPLACED", s)
with open("file.txt", "w") as wfile:
    wfile.write(rplce)

您可以使用更简单的方法。

with open('input_file.txt', 'r') as input_file:
   with open('output_file.txt', 'w') as output_file:
       for line in input_file:
           x = line.replace('findtext','replacetext')
           output_file.write(x)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM