我正在尝试从文本文件中读取坐标列表并将其插入到URL
中这是我的代码:
with open("coords.txt", "r") as txtFile:
for line in txtFile:
coords = line
url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=' + coords + '&radius=1&key=' + key
json_obj = urllib2.urlopen(url)
data = json.load(json_obj)
print data['results']
当我运行它时,我收到此错误:
Traceback (most recent call last):
File "C:\Users\Vel0city\Desktop\Coding\Python\placeid.py", line 8, in <module>
json_obj = urllib2.urlopen(url)
File "C:\Python27\lib\urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "C:\Python27\lib\urllib2.py", line 429, in open
req = meth(req)
File "C:\Python27\lib\urllib2.py", line 1125, in do_request_
raise URLError('no host given')
URLError: <urlopen error no host given>
我很确定这是因为python为文本文件中的每一行插入一个换行符,所以当我打印出连接到它的coords的最终url时,我得到了这个:
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.773972,-122.431297
&radius=1&key=
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.773972,-122.431297
&radius=1&key=
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.773972,-122.431297
&radius=1&key=
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.773972,-122.431297&radius=1&key=
我如何删除此换行符,以便它不会搞砸网址?
答案 0 :(得分:2)
您可以使用条method
coords = line.strip()
strip
什么也没做,只删除字符串中的空格。
如果您只想删除该行的一侧,则可以使用rstrip
和lstrip
修改强>
正如TemporalWolf在评论中提到的那样,strip方法可以用来去除空格旁边的其他东西(这是默认的)。
例如,line.strip('0')
将删除所有'0'次出现。