向与表达式(Python)匹配的行首和行尾添加字符

2024-07-04 17:16:51 发布

您现在位置:Python中文网/ 问答频道 /正文

背景:我的任务是从一个网站(主要是HTML表)获取内容,并将其插入wiki类型的网站。我能够使用restapi轮询内容(它是动态的),并获得HTML格式的输出。我必须获取这个输出,并将其转换为Wiki标记,然后将其插入到新站点中。我对转换部分有问题。你知道吗

目前我正在测试脚本中使用html2text模块,如下所示:

import os
import sys
import html2text

file = raw_input("File to convert: ")

h = html2text.HTML2Text()
with open(file, 'r') as f:
    dataContent = f.read()
    dataConverted = h.handle(dataContent)

with open('tempconvert', 'w') as f:
    f.write(dataConverted)
    #print dataConverted

# Add the | to the line beginnings and endings

with open('tempconvert', 'r') as f:
    tempContent = f.readlines()

with open('finalconvert', 'w') as f:
    for line in tempContent:
        if '|' in line:
            f.write('|' + line.rstrip('\n') + '| \n')

现在,所有这些输入和输出的原因是因为html2text模块没有插入wiki语法需要将其识别为表的开头或结尾“|”。你知道吗

我的问题是:

  1. 这太难看了。。。有没有什么方法可以在不写入这么多临时文件的情况下清除这些文件?你知道吗
  2. 当我使用final搜索添加“|”时,它只写它所作用的行(考虑到参数,这是有意义的)。我怎样才能让它对那些线起作用,同时又保留所有其他它不起作用的线呢?你知道吗
  3. 对于我来说,能够获取表实例的第一行(因为表前后都有空格,所以可以这么说)并附加一个“| |”来表示它的头行也是很棒的。这也可能吗?你知道吗

Tags: 模块toimport内容网站htmlaswith
2条回答

1:通过使用^{}将单个字符串转换为字符串列表,可以消除临时文件。这样做的副作用是从每一行中删除\n,您必须在后面添加或说明这些内容。你知道吗

tempContent = dataConverted.split('\n')

2:有两种方法可以解决这个问题。首先是简单地使用else来编写您之前跳过的行。(如果使用上面的split提示,则不需要rstrip)。你知道吗

if '|' in line:
    f.write('|' + line + '| \n')
else:
    f.write(line + '\n')

另一种方法是,如果行需要更新,则更新它,然后在任何情况下都写入它。你知道吗

if '|' in line:
    line = '|' + line + '| '
f.write(line + '\n')

3:这更难,因为你不只是想把这些条添加到一个空白行之后的任何一行,你想检测到有一个表出现了。这意味着你需要向前看。这里有一个小功能,你可以用它来自动看前面。你知道吗

def lookahead(seq):
    current = None
    for upcoming in seq:
        if current is not None:
            yield current, upcoming
        current = upcoming
    if current is not None:
        yield current, None

你可以这样使用它:

for line, upcoming in lookahead(tempContent):
    if (upcoming and '|' in upcoming) or ('|' in line):
        line = '|' + line + '|'

第一次尝试:

html = html2text.HTML2Text()
input_file = raw_input('File to convert: ')

with open(input_file, 'r') as input_, open('finalconvert', 'w') as output_:
    data = input_.read()
    data_converted = html.handle(data)

    for line in data_converted.split('\n'):
        if '|' in line:
            line = "|{}|\n".format(line.rstrip())
        output_.write(line.encode())

这段代码修复了1和2;但是我不理解3。你知道吗

相关问题 更多 >

    热门问题