简体   繁体   English

如何使用 python 将文本行转换为 HTML 链接?

[英]How do I convert lines of text into HTML links using python?

The code saves a list of URLs.该代码保存了一个 URL 列表。 I want to take the lines of text and covert them to links within an HTML file by adding the A tags and place those links within properly formatted HTML code.我想通过添加 A 标签将这些文本行转换为 HTML 文件中的链接,并将这些链接放置在格式正确的 HTML 代码中。

#!/usr/bin/env python

import sys
import os
import shutil

try: 
    from googlesearch import search 
except ImportError:  
    print("No module named 'google' found") 

#keyword query user input
query = raw_input('Enter keyword or keywords to search: ')

#print results from search into a file called keyword.txt
with open("keyword.txt","w+") as f:
     for j in search(query, tld='co.in', lang='en', num=10, start=0, stop=200, pause=3):
      f.write("%s\n" % j)
f.close() 

#add keyword to list of keywords file
sys.stdout=open("keywords","a+") 
print (query) 
sys.stdout.close()

#rename file to reflect query input
os.rename('keyword.txt',query + ".txt") 

#move created data file to proper directory and cleanup mess
source = os.listdir("/home/user/search/")
destination = "/home/user/search/index/"
for files in source:
    if files.endswith(".txt"):
    shutil.copy(files,destination)
os.remove(query + ".txt")

Expected results would be an HTML file with clickable links预期结果将是一个带有可点击链接的 HTML 文件

Based on your comment, it appears that you are struggling to write the url string obtained from the search function into a file along with the required HTML tags.根据您的评论,您似乎正在努力将从search功能获得的 url 字符串与所需的 HTML 标签一起写入文件。 Try:尝试:

with open("keyword.txt","w+") as f:
    for j in search(query, tld='co.in', lang='en', num=10, start=0, stop=200, pause=3):
        f.write('<a href="{0}">{1}</a> <br>\n'.format(j,j))

Which will write each url and add hyperlinks to the url.这将写入每个 url 并为该 url 添加超链接。 You might want to print <html> ... </html> and <body> ... </body> tags as well to keyword.txt .您可能还想将<html> ... </html><body> ... </body>标签打印到keyword.txt This can be done like这可以像

with open("keyword.txt","w+") as f:
   f.write('<html> \n <body> \n')
   for j in search(query, tld='co.in', lang='en', num=10, start=0, stop=200, pause=3):
      f.write('<a href="{0}">{1}</a> <br>\n'.format(j,j))
   f.write('\n</body> \n </html>')

And, you don't have to close the file using f.close() if you use with open see: https://stackoverflow.com/a/8011836/937153而且,如果您使用with open ,则不必使用f.close()关闭文件with open请参阅: https : f.close()

Personally, I prefer format over % .就个人而言,我更喜欢format不是% I will be careful about presenting a comparison between the two here.我会小心地在这里介绍两者之间的比较。 You can see Python string formatting: % vs. .format for a detailed discussion on this topic.您可以查看Python 字符串格式:% vs. .format以了解有关此主题的详细讨论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM