如何将文本从shell转换为html?

2024-04-29 05:53:02 发布

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

也许这真的是一个简单而愚蠢的问题,但我是Python新手,所以请处理它

我需要做的是——在shell中执行命令并将其输出为telegra.ph页面

问题-telegra.ph API忽略\n内容并在一行中输出所有文本

使用的Python电报API包装器-https://github.com/python273/telegraph

我知道它需要将我的文本转换为html格式并删除<;p>;标签,我尝试了一些脚本,但我的程序给了我错误:

telegraph.exceptions.NotAllowedTag: span tag is not allowed

所以,我删除了所有的span标记,得到了相同的结果,就好像我在没有转换的情况下放置了一样

然后我尝试使用replace("\n", "<p>"),但在结束标记时遇到了问题

代码:

import subprocess

from telegraph import Telegraph

telegraph = Telegraph()
telegraph.create_account(short_name='1111')

tmp = subprocess.run("arp", capture_output=True, text=True, shell=True).stdout

print( '\n\n\n'+tmp+'\n\n\n\n')   ### debug line


response = telegraph.create_page(
    'Random',
    html_content= '<p>' + tmp + '</p>'
)

print('https://telegra.ph/{}'.format(response['path']))

Tags: https标记文本importapitruehtmlshell
3条回答

我不清楚telegraph模块为什么用空格替换换行符。在这种情况下,禁用此功能似乎是合理的

import subprocess
import re

import telegraph
from telegraph import Telegraph

telegraph.utils.RE_WHITESPACE = re.compile(r'([ ]{10})', re.UNICODE)

telegraph = Telegraph()
telegraph.create_account(short_name='1111')

tmp = subprocess.run("/usr/sbin/arp", 
                     capture_output=True, 
                     text=True, 
                     shell=True).stdout
  
response = telegraph.create_page(
    'Random',
    html_content = '<pre>' + tmp + '</pre>'
)

print('https://telegra.ph/{}'.format(response['path']))

将输出

arp output formatted for telegraph

这接近于实际的格式化arp输出

\n最接近的html等价物是"hard break" ^{} tag
它不需要关闭,因为它不包含任何内容,直接表示换行

假设telegra.ph支持它,您可以简单地:

tmp.replace('\n', '<br/>');

添加此行可将所有中间换行符转换为单个换行符<;p>-章节:

tmp = "</p><p>".join(tmp.split("\n"))

tmp.split("\n")将字符串拆分为行数组

"</p><p>".join(...)再次将所有内容粘在一起,关闭上一个<;p>-并开始一个新的

这样,示例适用于我,换行符正确显示在页面上

编辑:正如另一个答案所建议的,您当然也可以使用
标记。这取决于你想要实现什么

相关问题 更多 >