全文共1191字,預計學習時長6分鐘
正則表達式是定義文本中搜索模式的特殊字符序列。「re.findall()」是Python中最基本的正則表達式函數之一,提取字符串表達式的開頭。本文將用這個函數告訴你,YouTube視頻標題與播放量之間的關係。test_string1= Python is Amazing!可將表達式r「^w+」與字符串一併傳遞至「re.findall」,這將返回輸入字符串的開頭:regex_1 =re.findall(r"^w+",test_string1)print(regex_1)在表達式r「^w+」中,字符「^」對應字符串開頭,而「w+」查找字符串中的字母數字字符。regex_1 =re.findall(r"w+",test_string1)print(regex_1)test_string2= Java is Amazing!現在,應用「re.findall()」查找該字符串的第一個單詞:regex_2 =re.findall(r"^w+",test_string2)print(regex_2)接下來,考慮一個更實際的場景。假設有一個YouTube視頻標題列表和相應的YouTube觀看次數。我們可能對分析視頻標題的第一個單詞和相應視頻觀看次數之間的關係感興趣。考慮以下標題/觀看次數元組列表:youtube_titles= [("How to Tell if We re Beating COVID-19", 2200000), ("ExtremeCloset Clean Out",326000), ("This is $1,000,000 inFood",8800000), ("How To Tell If Someone Truly Loves You ",2800000), ("How to Tell Real Gold from Fake", 2300000),("Extreme living room transformation ", 25000)]for titlein youtube_titles: print(re.findall(r"^w+",title[0])[0])first_words= []for title in youtube_titles: first_words.append(re.findall(r"^w+",title[0])[0])print(first_words)first_words= []views = []for title in youtube_titles: first_words.append(re.findall(r"^w+",title[0])[0]) views.append(title[1])importpandas as pddf = pd.DataFrame({ first_words : first_words, views :views})print(df)之後可以對每個標題首詞進行分組,並計算每個標題首詞的平均觀看次數:df =df.groupby( first_words )[ views ].mean()print(df)df =df.groupby( first_words )[ views ].mean().sort_values(ascending = False)print(df)假設這些結果來自一個足夠大的數據集(比如有數千個標題和觀看次數),這種類型的分析可以幫助我們選擇最佳的YouTube視頻標題。本文討論了如何使用python正則表達式模塊中的「re.findall()」函數。為提取每個字符串的第一個單詞,筆者將該函數應用於兩個簡單的字符串。然後,考慮了一個實際用例,使用該函數提取YouTube視頻標題的第一個單詞,並計算第一個單詞對應的平均觀看次數。https://towardsdatascience.com/regular-expressions-in-python-7c991daab100