如何搜索含指定任一话题标签且提及特定用户的Twitter推文
Let's break down how to build the right search query for your needs—you need tweets that have at least one of your target hashtags AND mention at least one of your specified users. Here's how to do it properly:
1. Understand Twitter Search Operators
First, the key operator you're missing is the uppercase OR—this is how you specify "either/or" conditions in Twitter's search syntax. Lowercase or won't work, so make sure to use all caps.
For "and" conditions, you can use the + operator (it makes the requirement explicit and avoids ambiguity).
2. Build the Query String
Combine your two sets of conditions with + (since both must be true):
- Hashtag group:
#EUwahl OR #Euwahlen OR #Europawahl OR #Europawahlen - User mention group:
@AfD OR @User2 OR @User3 OR @User4 OR @User5 OR @User6 OR @User7(replace the placeholders with your seven specific accounts)
Wrap each group in parentheses to make the logic crystal clear (this prevents confusion if you add more conditions later):
"(#EUwahl OR #Euwahlen OR #Europawahl OR #Europawahlen) + (@AfD OR @SPD OR @CDU OR @CSU OR @Gruene OR @FDP OR @Linke)"
(I used common German party accounts as examples—swap these with your actual target users.)
3. Update Your R Code
Plug this query into your searchTwitter() call. Here's the full working example:
# Define your combined search query search_query <- "(#EUwahl OR #Euwahlen OR #Europawahl OR #Europawahlen) + (@AfD OR @SPD OR @CDU OR @CSU OR @Gruene OR @FDP OR @Linke)" # Run the targeted search euelection <- searchTwitter(search_query, n = 1000, since = "2019-05-01", until = "2019-05-26")
4. Quick Tips
- Capitalization Matters:
ORmust be uppercase—Twitter's search engine ignores lowercaseorentirely. - Parentheses for Clarity: Using parentheses ensures the search engine evaluates each "or" group correctly before combining them with the "and" condition.
- API Limits: Keep in mind that Twitter's API has rate limits, and the
nparameter is a maximum (you might get fewer tweets if there aren't enough matching your criteria). - Package Alternatives: If you're using the newer
rtweetpackage instead oftwitteR, the search logic is identical—just usesearch_tweets()instead ofsearchTwitter().
内容的提问来源于stack exchange,提问作者Laura

