从python中的变音词创建url

时间:2014-11-22 16:45:06

标签: encoding urllib2 diacritics

我有这个示例代码。我读到了Requests的优越性。但是很久以前我用urllib2写了这篇文章。

我的问题是:

当我在 Spyder 中运行此代码时,它运行良好。但是当我使用python mycode.py从命令行(windows 8 64bit)运行它时会抛出错误。请问有谁请指导我如何解决这个问题?我需要从命令行运行它。非常感谢。

# -*- 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)

来自Spyder的结果:

<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 个答案:

答案 0 :(得分:2)

我从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)