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 读取文件并匹配多行_Python_Regex - Fatal编程技术网

Python 读取文件并匹配多行

Python 读取文件并匹配多行,python,regex,Python,Regex,文本文件如下所示: <field> </field> 我想匹配块,并在两个字段标记之间写入内容。我有下面的代码,它来自 /usr/bin/env蟒蛇3 导入mmap 导入操作系统 以open('sample.txt','rb+',0)作为文件\ mmap.mmap(file.fileno(),0,access=mmap.access\u READ)为s: 如果s.find(b'\n')!=-1: file.write(“你好”) 即使我使用

文本文件如下所示:

    <field>
        </field>

我想匹配块,并在两个字段标记之间写入内容。我有下面的代码,它来自

/usr/bin/env蟒蛇3
导入mmap
导入操作系统
以open('sample.txt','rb+',0)作为文件\
mmap.mmap(file.fileno(),0,access=mmap.access\u READ)为s:
如果s.find(b'\n')!=-1:
file.write(“你好”)
即使我使用\t检测选项卡,我的解决方案也不起作用

'<field>\n\t<\field>'
“\n\t”
我认为我的问题是如何匹配多行,其中有一些空间或制表符。谢谢大家

我的答案来自:

该解决方案不使用mmap。的确,我们不能将数据插入到文件中,但我们可以替换数据

        target = "<field>Hello</field>"

        with open(os.path.join(root, filename), 'r') as file:
            filedata = file.read()

        # Replace the target string
        filedata = filedata.replace('<field></field>', target)

        # Write the file out again
        with open(os.path.join(root, filename), 'w') as file:
            file.write(filedata)
target=“你好”
将open(os.path.join(root,filename),'r')作为文件:
filedata=file.read()
#替换目标字符串
filedata=filedata.replace(“”,目标)
#再把文件写出来
以open(os.path.join(root,filename),“w”)作为文件:
file.write(文件数据)

请参考此问题:

使用正则表达式的目标非常简单。下面的脚本在变量
html
中找到
标记,并将
放在标记之间

import mmap
import os
import re

# do logic here

# test for what you want from variable s:

a = re.sub('<field>(.*\n*)<\/field>', '<text to put between the tags>', html)
导入mmap
导入操作系统
进口稀土
#你在这里讲逻辑吗
#测试您想要从变量s中得到什么:
a=re.sub('(.*\n*)','',html)

(1)您不能将数据插入文件,您必须至少从插入点到结尾重写它。(2) 您调用了
find
,但没有使用它返回的位置。(3)
find
返回的位置将位于
b'
的开头。(4) 如果您是Python的初学者,那么应该从简单的内容开始:可能的副本必须参考mmaped文件:mm=mmap.mmap(file.fileno(),…)。请参阅文档,这里还有一个示例:
import mmap
import os
import re

# do logic here

# test for what you want from variable s:

a = re.sub('<field>(.*\n*)<\/field>', '<text to put between the tags>', html)