2012-05-14 150 views
1

在test.txt中,我有两行句子。为什么不能显示HTML代码?

The heart was made to be broken. 
There is no surprise more magical than the surprise of being loved. 

在代码:

import urllib2 
file = open('/Users/name/Desktop/textfile.txt','r') 
data = file.readlines() 
file.close() 
countline = 0 
for line in data: 
    countline = countline + 1 
    line_replace = line.replace(" ", "+") 
    line_url = 'http://sentistrength.wlv.ac.uk/results.php?text=' + line_replace + '&submit=Detect+Sentiment' 
    requesturl = urllib2.Request(line_url) 
    openurl = urllib2.urlopen(requesturl) 
    readurl = openurl.read() 
    print readurl 

我想打印出来的HTML代码。如果Textfile中只有一个句子。一切工作正常,但有一个错误,当有文本文件中的2个句子(我想显示这两个句子的HTML代码。)任何可能的方式来解决这个问题?

错误:

URLError: <urlopen error no host given>    
+2

http://docs.python.org/library/urllib.html#urllib .urlencode –

+0

'line_url'包含'\ n',尝试打印出该变量。 – Levon

回答

0

也许换行的文件是一个问题就在这里,请尝试:

line_replace = line.replace(" ", "+").strip("\n") 
+0

谢谢。这行得通。 (必须等待几分钟才能接受答案) – ThanaDaray