在字符串列表中搜索 2 个子字符串
Searching for 2 substrings in a list of strings
我正在尝试计算列表中子字符串的实例,但我很困惑如果一个值在列表中的同一字符串中有两个不同的子字符串,我该如何计算。这是我当前的程序,第 11 行是我不确定要做什么的地方。
import json
FILENAME = "superbowltweets.json"
def main():
with open(FILENAME) as file:
data = json.load(file)
tweets = [tweet["full_text"] for tweet in data]
rams_count = has_rams("rams", tweets)
pats_count = has_pats("pat", tweets)
both_count = has_both("pats rams", tweets)
def has_rams(sub_str, tweets):
rams_count = len([s for s in tweets if sub_str in s])
print("There are " +str(rams_count) + " tweets about the Rams")
return rams_count
def has_pats(sub_str, tweets):
pats_count = len([s for s in tweets if sub_str in s])
print("There are " +str(pats_count) + " tweets about the Patriots")
return pats_count
def has_both(sub_str, tweets):
both_count = len([s for s in tweets if sub_str in s])
print("There are " + str(both_count) + " tweets that mention both")
if __name__=="__main__":
main()
这里是推文列表的一小段:
["lets go rams!", "patriots suck and the rams are going to win!", "I hate tom brady", "rams should go back to saint louis"]
我想检查列表 tweets
中的值是否同时包含“rams”和“pats”,然后将该数字分配给一个变量。我想保留我目前的功能。
您可以将has_both修改为:
def has_both(sub_str1, sub_str2, tweets):
both_count = len([s for s in tweets if (sub_str1 in s) and (sub_str2 in s)])
print("There are " + str(both_count) + " tweets that mention both")
正确,应该是and。
我正在尝试计算列表中子字符串的实例,但我很困惑如果一个值在列表中的同一字符串中有两个不同的子字符串,我该如何计算。这是我当前的程序,第 11 行是我不确定要做什么的地方。
import json
FILENAME = "superbowltweets.json"
def main():
with open(FILENAME) as file:
data = json.load(file)
tweets = [tweet["full_text"] for tweet in data]
rams_count = has_rams("rams", tweets)
pats_count = has_pats("pat", tweets)
both_count = has_both("pats rams", tweets)
def has_rams(sub_str, tweets):
rams_count = len([s for s in tweets if sub_str in s])
print("There are " +str(rams_count) + " tweets about the Rams")
return rams_count
def has_pats(sub_str, tweets):
pats_count = len([s for s in tweets if sub_str in s])
print("There are " +str(pats_count) + " tweets about the Patriots")
return pats_count
def has_both(sub_str, tweets):
both_count = len([s for s in tweets if sub_str in s])
print("There are " + str(both_count) + " tweets that mention both")
if __name__=="__main__":
main()
这里是推文列表的一小段:
["lets go rams!", "patriots suck and the rams are going to win!", "I hate tom brady", "rams should go back to saint louis"]
我想检查列表 tweets
中的值是否同时包含“rams”和“pats”,然后将该数字分配给一个变量。我想保留我目前的功能。
您可以将has_both修改为:
def has_both(sub_str1, sub_str2, tweets):
both_count = len([s for s in tweets if (sub_str1 in s) and (sub_str2 in s)])
print("There are " + str(both_count) + " tweets that mention both")
正确,应该是and。