2014-11-22 35 views
0

我有这个示例代码。我了解了请求的优越程度。但是我很久以前用urllib2写了这个。使python中的变音词词汇url

我的问题是:

当我运行这段代码Spyder的它的作品不错。但是当我从命令行(Windows 8 64位)使用python mycode.py运行它时,它会引发错误。请有人指导我如何解决这个问题?我需要从命令行运行它。非常感谢。从Spyder的

# -*- coding: utf-8 -*- 

import urllib2 

city = u'Köln' 


def make_url(word): 
    Word = unicode(word) 
    print type(Word)  
    url_Word = urllib2.quote(Word, "utf-8") 
    print "\ntype = %s \n" %type(Word) 
    print "url_word = %s \n" %url_Word 


make_url(city) 

结果:在命令行

<type 'unicode'> 

type = <type 'unicode'> 

url_word = K%F6ln 

结果:

<type 'unicode'> 
C:\Python27\lib\urllib.py:1285: UnicodeWarning: Unicode equal comparison failed 
to convert both arguments to Unicode - interpreting them as being unequal 
    return ''.join(map(quoter, s)) 
Traceback (most recent call last): 
    File "to_Ask_question.py", line 21, in <module> 
    make_url(city) 
    File "to_Ask_question.py", line 16, in make_url 
    url_Word = urllib2.quote(Word, "utf-8") 
    File "C:\Python27\lib\urllib.py", line 1285, in quote 
    return ''.join(map(quoter, s)) 
KeyError: u'\xf6' 

回答

1

我有想法来自this question

通过只是转换为字符串喂养urllib2.quote()

这里之前是代码:

import urllib2 
import codecs 

city = u'Köln' 

def make_url(word): 
    word = codecs.encode(word,'utf-8') 
    print type(word)  
    url_Word = urllib2.quote(word) 
    print "\ntype = %s \n" %type(word) 
    print "url_word = %s \n" %url_Word 


make_url(city)