Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中使用regex包替换文本文件?_Python_Regex_Python 3.x_Python 3.6 - Fatal编程技术网

如何在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文件:
以读取模式自动打开文件。你没有写任何东西回文件。有很多关于阅读和写作文件的教程和问答。我阅读了每个关于堆栈溢出的论坛。没有任何东西可以帮助我
替换
不编辑字符串;它返回一个新字符串。字符串是不可变的。看起来您认为它替代了文件路径内容。