【发布时间】:2014-06-13 16:21:48
【问题描述】:
我编写了这段代码来用它们的标题替换 url。它确实会根据需要用标题替换 url,但它会在下一行打印它们的标题。
twfile.txt 包含以下几行:
link1 http://t.co/HvKkwR1c
no link line
输出tw2文件:
link1
Instagram
no link line
但我想以这种形式输出:
link1 Instagram
no link line
我该怎么办?
我的代码:
from bs4 import BeautifulSoup
import urllib
output = open('tw2file.txt','w')
with open('twfile.txt','r') as inputf:
for line in inputf:
try:
list1 = line.split(' ')
for i in range(len(list1)):
if "http" in list1[i]:
##print list1[i]
response = urllib.urlopen(list1[i])
html = response.read()
soup = BeautifulSoup(html)
list1[i] = soup.html.head.title
##print list1[i]
list1[i] = ''.join(ch for ch in list1[i])
else:
list1[i] = ''.join(ch for ch in list1[i])
line = ' '.join(list1)
print line
output.write(line)
except:
pass
inputf.close()
output.close()
【问题讨论】:
标签: python url python-2.7 beautifulsoup urllib