简体   繁体   English

在 python 中使用 Tweepy 的正则表达式错误

[英]Regex errors utilizing Tweepy in python

I am having a problem with the bit of code shown below.我对下面显示的代码有问题。 My original code worked when I was just puling the tweet information.当我刚刚推送推文信息时,我的原始代码有效。 Once I edited it to extract the URL within the text it started to give me problems.一旦我对其进行编辑以提取文本中的 URL,它就开始给我带来问题。 Nothing is printing and I am receiving these errors.什么都没有打印,我收到这些错误。

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

I am receiving no errors before I run it, so I am extremely confused about why this is not working.在运行它之前我没有收到任何错误,所以我对为什么这不起作用感到非常困惑。 It will probably be something simple as I am new to using both Tweepy and Regex.这可能会很简单,因为我不熟悉使用 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")

Errors again:再次出现错误:

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

Process finished with exit code 1

Tell me if you need more information to help me, any help is appreciated, thanks in advance.如果您需要更多信息来帮助我,请告诉我,任何帮助表示赞赏,在此先感谢。

You're getting that error because you are using a string pattern (your regex) against a string which you've turned into a bytes object via encode() .您收到该错误是因为您对已通过encode()

Try running your pattern directly against tweet.text without encoding it.尝试直接针对tweet.text运行您的模式而不对其进行编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM