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