问题描述
我对下面显示的代码位有问题。当我只是提取推文信息时,我的原始代码有效。一旦我编辑它以提取文本中的 URL,它就开始给我带来问题。什么都没有打印,我收到了这些错误。
Traceback (most recent call last):
File "C:\Users\Evan\PycharmProjects\discordBot1\main.py",line 22,in <module>
get_tweets(api,"cnn")
File "C:\Users\Evan\PycharmProjects\discordBot1\main.py",line 18,in get_tweets
url2 = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',text)
File "C:\Users\Evan\AppData\Local\Programs\Python\python39\lib\re.py",line 241,in findall
return _compile(pattern,flags).findall(string)
TypeError: cannot use a string pattern on a bytes-like object
我在运行之前没有收到任何错误,所以我对为什么这不起作用感到非常困惑。这可能很简单,因为我不熟悉使用 Tweepy 和 Regex。
import tweepy
import re
TWITTER_APP_SECRET = 'hidden'
TWITTER_APP_KEY = 'hidden'
auth = tweepy.OAuthHandler(TWITTER_APP_KEY,TWITTER_APP_SECRET)
api = tweepy.API(auth)
def get_tweets(api,username):
page = 1
while True:
tweets = api.user_timeline(username,page=page)
for tweet in tweets:
text = tweet.text.encode("utf-8")
url2 = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-
F]))+',text)
print(url2)
get_tweets(api,"cnn")
再次出错:
Traceback (most recent call last):
File "C:\Users\Evan\PycharmProjects\discordBot1\main.py",flags).findall(string)
TypeError: cannot use a string pattern on a bytes-like object
Process finished with exit code 1
如果您需要更多信息来帮助我,请告诉我,感谢您的帮助,提前致谢。
解决方法
您之所以收到该错误,是因为您对通过 encode()
转换为字节对象的字符串使用了字符串模式(您的正则表达式)。
尝试直接针对 tweet.text
运行您的模式,而不对其进行编码。