【问题标题】:Create hyperlinks from urls in text file using QTextBrowser使用 QTextBrowser 从文本文件中的 url 创建超链接
【发布时间】:2018-08-01 04:32:11
【问题描述】:

我有一个包含一些基本文本的文本文件:

For more information on this topic, go to (http://moreInfo.com)
This tool is available from (https://www.someWebsite.co.uk)
Contacts (https://www.contacts.net)

我希望 url 在QTextBrowser 中显示为超链接,以便在单击时,Web 浏览器将打开并加载网站。我见过this post 使用:

<a href="http://foo">Bar</a>

但由于任何人都可以编辑文本文件(即它们可能包含不提供网址的文本),我希望这些地址(如果有)可以在添加到文本浏览器之前自动超链接.

这就是我阅读文本文件的方式:

def info(self):
    text_browser = self.dockwidget.text_browser
    file_path = 'path/to/text.txt'
    f = open(file_path, 'r')
    text = f.read()
    text_browser.setText(text)
    text_browser.setOpenExternalLinks(True)
    self.dockwidget.show()

编辑:

取得了一些进展并设法使用(假设链接在括号内)获取超链接:

import re

def info(self):
    text_browser = self.dockwidget.text_browser
    file_path = 'path/to/text.txt'
    f = open(about_file_path, 'r')
    text = f.read()
    urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', text)

    for x in urls:
        if x in text:
            text = text.replace(x, x.replace('http', '<a href="http').replace(')', '">') + x + '</a>')

    textBrowser.setHtml(text)
    textBrowser.setOpenExternalLinks(True)
    self.dockwidget.show()

但是,它全部出现在一行中,并且与文本文件中的格式不同。我该如何解决这个问题?

【问题讨论】:

  • @ekhumoro - 感谢您的链接,确实很复杂!但是您保留换行符的建议对我来说已经足够了,您能否发表您的评论作为答案? :)

标签: python parsing hyperlink pyqt qtextbrowser


【解决方案1】:

正确匹配网址比您当前的解决方案可能建议的要复杂。有关问题的完整细分,请参阅:What is the best regular expression to check if a string is a valid URL?

另一个问题更容易解决。要保留换行符,您可以使用:

text = '<br>'.join(text.splitlines())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    相关资源
    最近更新 更多