【问题标题】:How do I resolve a TypeError on startswith in python?python - 如何在python中解决startswith上的TypeError?
【发布时间】:2015-06-29 18:20:01
【问题描述】:

使用:Python 3.4

我正在尝试从这里使用维基百科脚本/模块:

http://pastebin.com/FVDxLWNG (wikipedia.py)

http://pastebin.com/idw8vQQK (wiki2plain.py)

我遇到的问题是以下代码:

def article(self, article):
    url = self.url_article % (self.lang, urllib.parse.quote_plus(article))
    content = self.__fetch(url).read()

    if content.upper().startswith("#REDIRECT"): 
        match = re.match('(?i)#REDIRECT \[\[([^\[\]]+)\]\]', content)

        if not match == None:
            return self.article(match.group(1))

        raise WikipediaError('Can\'t found redirect article.')

    return content

如果我运行它,我会收到错误:“startswith first arg must be bytes or a tuple of bytes, not str”,所以我将其更改为

if content.upper().startswith(b"#REDIRECT"): 

它运行正常。然后,当我尝试使用它时,我在某处得到“TypeError: can't use a string pattern on a bytes-like object”。我已经更改了一些脚本以在 3.4 中工作,但我似乎并没有让它工作。如何解决startswith 上的TypeError 问题?

文件“C:\Anaconda3\lib\re.py”,第 179 行,在 sub return _compile(pattern, flags).sub(repl, string, count)

TypeError: can't use a string pattern on a bytes-like object

【问题讨论】:

  • 你怎么知道你的TypeErrorstartswith?鉴于它来自re.py 并提到_compile 和“字符串模式”,也许它是下一个re.match 行?
  • 尝试使下一行中的字符串成为字节串-。它可能还需要是一个原始字符串 (r"foo")。
  • 也许你也应该改变正则表达式:match = re.match(b'(?i)#REDIRECT \[\[([^\[\]]+)\]\]', content)
  • @AmitKumarGupta:你是对的。重新匹配是问题所在。我最终通过使用str(variablename) 转换从wiki 挖掘的数据变量来更改代码,然后只像以前一样继续使用代码。我检查了这个,一旦检索到数据,它确实是一个巨大的字节串。转换为字符串就可以了。感谢您的帮助!

标签: python


【解决方案1】:

您应该通过适当的编码来解码内容。

试试这个,而不是content = self.__fetch(url).read()

result = self.__fetch(url)
content = result.read().decode(result.headers.get_content_charset())

【讨论】:

    猜你喜欢
    • 2014-02-20
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 2013-12-12
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多