使用python正则表达式在两个文件之间进行子操作

时间:2013-05-20 13:57:06

标签: python regex python-2.7

基本上我正在尝试从文本文件中读取文本,使用正则表达式将其转换为其他内容,然后将其写入html文件。

这是我所拥有的片段:

from re import sub

def markup():
    ##sub code here
    sub('[a-z]+', 'test', file_contents)

问题似乎与该子线有关。 下面的代码(同一个函数的一部分)需要用带有底层文本的html文件。

    ## write the HTML file
    opfile = open(output_file, 'w') 
    opfile.write('<html>\n')    
    opfile.write('<head>\n') 
    opfile.write('<title>') 
    opfile.write(file_title) 
    opfile.write('</title>\n') 
    opfile.write('</head>\n') 
    opfile.write('<body>\n')
    opfile.write(file_contents)
    opfile.write('</body>\n')
    opfile.write('</html>')
    opfile.close()

此处的功能设计为可以从多个文件中取出文本。在调用标记函数后,我可以复制file_contents之后的所有内容,除了括号中的东西,我将替换为其他文件的名称。

def content_func():
    global file_contents
    global file_title
    global output_file
    file_contents = open('example.txt', 'U').read()
    file_title = ('example')
    output_file = ('example.html')
    markup()

content_func()

Example.txt只是一个文本文件,其中包含“快速棕色狐狸跳过懒狗”的文字。我希望实现的是搜索特定标记语言的文本并用HTML标记替换它,但我在这里简化它以帮助我尝试解决它。​​

运行此代码理论上应该创建一个名为example.html的html文件,标题和文本说“test”,但事实并非如此。我不熟悉正则表达式,他们让我发疯。任何人都可以建议我应该用正则表达式'sub'做什么?

编辑:代码不会产生任何错误,但输出HTML文件缺少任何替换文本。所以sub正在搜索外部文本文件,但没有将它放入输出HTML文件中。

1 个答案:

答案 0 :(得分:1)

您永远不会保存sub()的结果。取代

sub('[a-z]+', 'test', file_contents)

用这个

file_contents = sub('[a-z]+', 'test', file_contents)