如何在python中使用regex包替换文本文件?
我在一个大的文本文件中查找模式,然后删除模式并打印文本。但是,我试图用不带模式的如何在python中使用regex包替换文本文件?,python,regex,python-3.x,python-3.6,Python,Regex,Python 3.x,Python 3.6,我在一个大的文本文件中查找模式,然后删除模式并打印文本。但是,我试图用不带模式的new_text替换文件中的旧文本(带模式) 我用的是regex软件包,不管我怎么尝试,它都不起作用 我的命令.replace不起作用 import re rgx_list = ['Read More', 'Read', 'And follow us on Twitter to keep up with the latest news and and acute an
new_text
替换文件中的旧文本(带模式)
我用的是regex软件包,不管我怎么尝试,它都不起作用
我的命令.replace
不起作用
import re
rgx_list = ['Read More',
'Read',
'And follow us on Twitter to keep up with the latest news and and acute and primary Care.',...]
txt_path = '/Users/sofia/Documents/src/fakenews1/data/news-data/war_sc_r.txt'
with open(txt_path) as new_txt_file:
new_text = new_txt_file.read()
for rgx_match in rgx_list:
new_text = re.sub(rgx_match, '', new_text)
new_text.replace(txt_path, new_text)
print(new_text)
谢谢大家! 我不明白您为什么要使用
replace()
函数。也许你可以读一下你的文档。如果要将new_text
写入文件,应在write
模式下再次打开文件,然后将新内容写入文件
import re
rgx_list = ['Read More',
'Read',
'And follow us on Twitter to keep up with the latest news and and acute and primary Care.']
txt_path = 'newyorktimes_test.txt'
with open(txt_path) as new_txt_file:
new_text = new_txt_file.read()
for rgx_match in rgx_list:
new_text = re.sub(rgx_match, '', new_text)
with open(txt_path, 'w') as new_txt_file:
new_txt_file.write(new_text)
如果您正在寻找一种更有效的方法,那么有一些库可以帮助您进行谷歌搜索。
使用open(txt\u路径)作为新的txt\u文件:
以读取模式自动打开文件。你没有写任何东西回文件。有很多关于阅读和写作文件的教程和问答。我阅读了每个关于堆栈溢出的论坛。没有任何东西可以帮助我替换不编辑字符串;它返回一个新字符串。字符串是不可变的。看起来您认为它替代了文件路径内容。