Python 如何返回包含给定hashtag的所有字符串的列表?
以下是我目前的代码: 第一区-推特类, 第二块-推文输入列表, 第三个街区-功能我正在努力工作。 第四块-预期输出Python 如何返回包含给定hashtag的所有字符串的列表?,python,Python,以下是我目前的代码: 第一区-推特类, 第二块-推文输入列表, 第三个街区-功能我正在努力工作。 第四块-预期输出 class Tweet: “”“Tweet类。”“” 定义初始化(self,用户:str,内容:str,时间:float,转发:int): """ Tweet构造函数。 :param user:tweet的作者。 :param content:tweet的内容。 :param time:tweet的年龄。 :param retweets:转发的数量。 """ self.user=用
class Tweet:
“”“Tweet类。”“”
定义初始化(self,用户:str,内容:str,时间:float,转发:int):
"""
Tweet构造函数。
:param user:tweet的作者。
:param content:tweet的内容。
:param time:tweet的年龄。
:param retweets:转发的数量。
"""
self.user=用户
self.content=内容
self.time=时间
self.retweets=转发
我尝试了很多正则表达式库操作,但不知何故,filtered_by_hashtag函数中返回的列表总是空的,我知道问题出在for循环中的if子句中,但是我仍然无法解决这个问题。对此,您甚至不需要正则表达式--中的Python基本
操作符就可以了
from typing import List
def filter_by_hashtag(tweets: List[Tweet], hashtag: str) -> List[Tweet]:
return [t for t in tweets if hashtag in t.content]
您是否尝试删除其他声明?
def filter_by_hashtag(tweets: list, hashtag: str) -> list:
"""
Filter tweets by hashtag.
Return a list of all tweets that contain given hashtag.
:param tweets: Input list of tweets.
:param hashtag: Hashtag to filter by.
:return: Filtered list of tweets.
"""
import re
filtered_lst = []
hashtag = re.compile(r'#\w+')
for tweet in tweets:
if hashtag in re.findall(r'#\w+', tweet.content):
filtered_lst.append(tweet)
else:
break
return filtered_lst
print(filter_by_hashtag(tweets, "#bigsmart"))
filtered_lst = [("@realDonaldTrump", "Despite the negative press covfefe #bigsmart", 1249, 54303), ("@realDonaldTrump", "Despite the negative press covfefe #bigsmart", 1249, 54303)]
from typing import List
def filter_by_hashtag(tweets: List[Tweet], hashtag: str) -> List[Tweet]:
return [t for t in tweets if hashtag in t.content]