【问题标题】:Is there a better or more efficient way to code this?有没有更好或更有效的编码方式?
【发布时间】:2013-11-24 14:22:20
【问题描述】:
import re
fr=open("test.html",'r')
i,j,tablestart=0,0,0
str=""
p=re.compile("<td.*?>(.*?)<\/td>")
for line in fr:
    if "<table" in line:
        tablestart=1
    elif "</table>" in line and tablestart==1:
        j,tablestart=0,0
    m=p.search(line)
    if m and tablestart==1:
        str+='"' + m.group(1) + '"' + ","
    if "</tr>" in line and tablestart==1:
        print(str)
        str=""

代码是从 html 表创建 csv 文件。 有没有更好或更有效的编码方式? 我不是在寻找任何 html 解析器。

【问题讨论】:

  • "我不是在寻找任何 html 解析器。" - 为什么? 会是更好的方法。
  • 我喜欢先编写我需要的东西,然后再使用其他人的代码。如果一行中有两个 我有什么建议?
  • 您的代码假定 html 由换行符分割,这并不总是正确的,整个表格可以在一行中。我也会去解析器。
  • 请查看此问题的最高投票答案:stackoverflow.com/questions/1732348/…
  • 关于你的正则表达式。如果你的 html 包含例如会发生什么&lt;a onClick="javascript:alert(3 &gt; 2)"&gt;。说真的,你不能用正则表达式解析非常规语法。

标签: python regex html-table export-to-csv


【解决方案1】:

可能是这样的:

for line in fr:
   if re.search(r'"<td.*?>.+?<\/td>"',line):
      line_table = re.findall(r'\>\.+?\<',line)
      var = line_table
      for var1 in var:
         if var1 != False:
             var2 = re.findall(r'\>\.+?\<',var1)[0]
             output.write(var2+','+'\n')
         else:
             output.write(','+'\n')

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签