使用通配符re.match找到文件中的行后,修改它

时间:2015-04-17 23:43:40

标签: python regex

我试图在使用socket检索值后动态地重写一个超级简单的html页面。基本上这是从我的squeezebox中拉出一个曲目名称并尝试将其写入html。行的第一部分始终相同,但轨道标题需要更改。我确定它非常简单,但我花了几个小时拖网浏览不同的网站并查看差异方法,所以有时间寻求帮助。

HTML中有一行,如下所示:

<p class="GeneratedText">Someone Like You</p>

然后我尝试运行以下内容来查找该行。它始终是相同的行号,但我尝试使用读取行,我读到它仍然读取所有内容:

import socket
import urllib
import fileinput
import re
# connect to my squeebox - retricve the track name and clean up ready for insertion
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(("192.168.1.10", 9090))
clientsocket.send("00:04:00:00:00:00 title ?\n")
str = clientsocket.recv(100)
title=str.strip( '00%3A00%3A00%3A00%3A00%3A00 title' );
result = urllib.unquote(title)
#try and overwrite the line in we.html so it looks like <p class="GeneratedText">Now playing track</p>
with open('we.html', 'r+') as f:
        for line in f:
           if re.match("(.*)p class(.*)",line):
              data=line
              print data
              f.write( line.replace(data,'<p class="GeneratedText">'title'</p>'))

3 个答案:

答案 0 :(得分:1)

快速解决方案可能是使用您尝试导入的fileinput module

因此,您的代码看起来像这样:

  for line in fileinput.input('we.html', inplace=True):
    if re.match("(.*)p class(.*)",line):
        print line.replace(line, '<p class="GeneratedText">' + title + '</p>')
    else:
        print line

您必须将with块替换为上面的

但是,如果您想要一个更干净的解决方案,您应该查看Beautiful Soup,这是一个用于操作结构化文档的python库。

您仍然需要通过pip安装模块,然后导入BeautifulSoup,但此代码可让您随后运行:

with open('we.html', 'r') as html:
    soup = BeautifulSoup(html)

for paragraph in soup.find_all('p', class_='GeneratedText'):
    paragraph.string = title

with open('we.html', 'w') as html:
    html.write(soup.prettify('utf-8'))

答案 1 :(得分:0)

如果您在整个页面中只出现过一次,则可以执行以下操作:

new_html = re.sub('(?<=<p class="GeneratedText">)(.*)(?=<\/p>)',
                  "WhateverYouWantGoesHere",
                   html_file_as_string)

它将以您想要的任何内容替换2个标签之间的所有内容。

答案 2 :(得分:0)

with open('output.html', 'w') as o:
    with open('we.html', 'r') as f:
        for line in f:
            o.write(re.sub("(?:p\sclass=\"GeneratedText\">)(\w+\s?)+(:?</p>)", newTitle, line))