1

在 test.txt 中,我有 2 行句子。

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 中只有 1 个句子。一切正常,但是当文本文件中有 2 个句子时出现错误(我想显示两个句子的 html 代码。)有什么可能的方法来解决这个问题?

错误:

URLError: <urlopen error no host given>             
4

1 回答 1

0

也许文件中的换行符在这里有问题,请尝试:

line_replace = line.replace(" ", "+").strip("\n")
于 2012-05-14T10:44:28.760 回答