呃!不适合我!
在找到正向推文后,您还想处理负向推文。现在的计划是查找包含单词 hate、dislike 或 disapprove 的句子。您仍然要保存电影或演唱会的名称。您会匹配到包含单词 movie 或 concert 的推文,但这次不打算保存该单词。
例如,若有句子:I dislike the movie Avengers a lot.。您需要匹配并捕获 dislike。您会匹配但不捕获单词 movie。随后,您匹配并捕获直到句号之前的所有内容。
列表 sentiment_analysis(包含 3 条推文的文本)以及 re 模块已加载到您的会话中。您可以使用 print() 在 IPython Shell 中查看数据。
本练习是课程的一部分
Python 中的正则表达式
练习说明
- 完成正则表达式以捕获单词
hate、dislike或disapprove。匹配但不捕获单词movie或concert。匹配并捕获直到.之前出现的任何内容。 - 在
sentiment_analysis的每个元素中查找该正则的所有匹配项。将结果赋给negative_matches。 - 完成
.format()方法,打印出sentiment_analysis各元素对应的negative_matches中的结果。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Write a regex that matches sentences with the optional words
regex_negative = r"____.+?____\s____\."
for tweet in sentiment_analysis:
# Find all matches of regex in tweet
negative_matches = re.____(____, ____)
# Complete format to print out the results
print("Negative comments found ____".format(____))