python代码重复输出文本,但只希望输出一次

python代码重复输出文本,有没帅哥美女看看。
Welcome to a simple file.

there are not many things to say.

just one thing is exact that is "feigou Linfan".web is 'www.4399.com' and email is feigou@2003.com
上面三行英文是我文本的内容,我期待输出三行,结果

img

下面给出全部代码
这个是H5文本块生成器.py

import logging
logging.basicConfig(level=logging.INFO, filename='H7mylog.log')


def lines(file):
    for line in file:
        yield line
    yield '\n'


def blocks(file):
    block = []
    logging.info('www  circulation   www')
    for line in lines(file):

        if line.strip():
            block.append(line)
            logging.info('read line')
        elif block:
            yield ''.join(block).strip()
            logging.info('write block')
            block = []

这个是H9handlers.py

class Handler:

    def callback(self, prefix, name, *args):
        method = getattr(self, prefix + name, None)
        if callable(method):
            return method(*args)

    def start(self, name):
        self.callback('start_', name)

    def end(self, name):
        self.callback('end_', name)

    def sub(self, name):
        def substitution(match):
            result = self.callback('sub_', name, match)
            if result is None:
                match.group(0)
            return result
        return substitution


class HTMLRenderer(Handler):

    def start_document(self):
        print('<html><head><title>...</title></head><body>')

    def end_document(self):
        print('</body></html>')

    def start_paragraph(self):
        print('<p>')

    def end_paragraph(self):
        print('</p>')

    def start_heading(self):
        print('<h2>')

    def end_heading(self):
        print('</h2>')

    def start_list(self):
        print('<ul>')

    def end_list(self):
        print('</ul>')

    def start_listitem(self):
        print('<li>')

    def end_listitem(self):
        print('</li>')

    def start_title(self):
        print('<h1>')

    def end_title(self):
        print('</h1>')

    def sub_emphasis(self, match):
        return '<em>{}</em>'.format(match.group(1))

    def sub_url(self, match):
        return '<a href="{}">{}</a>'.format(match.group(1), match.group(1))

    def sub_mail(self, match):
        return '<a href="mailto:{}">{}</a>'.format(match.group(1), match.group(1))

    def feed(self, data):
        print(data)


这个是H91rules.py

class Rule:

    def action(self, block, handler):
        handler.start(self.type)
        handler.feed(block)
        handler.end(self.type)
        return True


class HeadingRule(Rule):
    type = 'heading'

    def condition(self, block):
        return not '\n' in block and len(block) <= 70 and not block[-1] == ':'


class TitleRule(HeadingRule):
    type = 'title'
    first = True

    def condition(self, block):
        if not self.first:
            return False
        return HeadingRule.condition(self, block)


class ListItemRule(Rule):
    type = 'listitem'

    def condition(self, block):
        return block[0] == '-'

    def action(self, block, handler):
        handler.start(self.type)
        handler.feed(block[1:].strip())
        handler.end(self.type)
        return True


class ListRule(ListItemRule):
    type = 'list'
    inside = False

    def condition(self, block):
        return True

    def action(self, block, handler):
        if not self.inside and ListItemRule.condition(self, block):
            handler.start(self.type)
            self.inside = True
        elif self.inside and not ListItemRule.condition(self, block):
            handler.end(self.type)
            self.inside = False
        return False


class ParagraphRule(Rule):
    type = 'paragraph'

    def condition(self, block):
        return True

最后是主程序H92markup.py

import re
from H5文本块生成器 import *
from H9handlers import *
from H91rules import *
f = open(r'C:\Users\a\Desktop\纯文本文档.txt')


class Parser:

    def __init__(self, handler):
        self.handler = handler
        self.rules = []
        self.filters = []

    def addRule(self, rule):
        self.rules.append(rule)

    def addFilter(self, pattern, name):
        def filter(block, handler):
            return re.sub(pattern, handler.sub(name), block)
        self.filters.append(filter)

    def parser(self, file):
        self.handler.start('document')
        for block in blocks(file):  # 第一次仅读取了一行文本, 并没有变成块
            logging.info('@@@@@@@@@@circulation@@@@@@@@@@@@')
            for filter in self.filters:
                logging.info('use filter')  # 字符串中的部分字符被指定方式handler替换
                block = filter(block, self.handler)
                for rule in self.rules:   # 自动添加标签
                    logging.info('use rule')
                    if rule.condition(block):
                        logging.info('print 3 lines')
                        last = rule.action(block, self.handler)    # 三行字符串
                        if last:  # 这里有问题,不知道为什么不执行这个判断语句,直到第二次循环
                            logging.info('-------------------break-------------------')
                            break


class BasicTextParser(Parser):
    def __init__(self, handler):
        Parser.__init__(self, handler)
        self.addRule(ListRule())
        self.addRule(ListItemRule())
        self.addRule(TitleRule())
        self.addRule(HeadingRule())
        self.addRule(ParagraphRule())

        self.addFilter(r'\*(.+?)\*', 'emphasis')
        self.addFilter(r'(http://[\.a-zA-Z/]+)', 'url')
        self.addFilter(r'[\.a-zA-Z]+@[\.a-zA-Z+[a-zA-Z]+', 'mail')


handler = HTMLRenderer()
parser = BasicTextParser(handler)

parser.parser(f)

  • 应该是您重复调用函数了,我查找半天都没找到。
    您的函数太多了,加载用的*,全部函数都在一个作用域,调用时记不了那么多函数名,且容易造成不同模块的同名函数被覆盖而引发异常。一般import不建议用*,全部载入,特别是模块中的东西很多的情况。

  • 您能说说,您的那一大片代码,要完成的功能么?
    我能看出来的是,您想把您的纯文本用python代码“自动”成html5源码,不知是也不是😋
    我尝试过生成简单HTML5页面源码,不断调试后,在csdn博文笔记页面,显示还算将就。我感觉您所用的函数太多了,运用“插值字符串格式化”模板化生成一些标签,您的代码可以更加轻盈。



【以下回答由 GPT 生成】

优化建议:

你可以尝试在代码中使用日志记录器(logging)来跟踪代码的执行过程。以下是你的代码示例,我为你添加了一些注释来说明每个部分的作用:

import logging

def lines(file):
    for line in file:
        yield line
    yield '\n'

def blocks(file):
    block = []
    logging.info('开始处理文件')
    for line in lines(file):
        if line.strip():
            block.append(line)
            logging.info('读取到一行文本')
        elif block:
            yield ''.join(block).strip()
            logging.info('输出一个文本块')
            block = []

logging.basicConfig(level=logging.INFO, filename='H7mylog.log')

# 在适当的位置调用blocks函数来处理文件

另外,你提到希望输出三行文本,但实际上你的代码中并没有明确要求输出这三行文本。如果你想要输出这三行文本,请确保在调用blocks函数之后添加以下代码:

with open('your_file.txt', 'r') as file:  # 替换为你的文件路径
    for block in blocks(file):
        print(block)  # 输出文本块内容

这样你就能在控制台中看到每个文本块的内容了。记得将'your_file.txt'替换为你实际的文件路径。

希望这些信息对你有所帮助!如果还有其他问题,请随时提问。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^

用logging找了下,发现是break位置有问题,要跟for对齐。改了之后,发现rule类有点问题,一行文字可以相应三四个rule,但是我这里除了开头可能会响应两边外,其它文本只需要响应一次。到时候再看看吧