全文共1191字,預計學習時長
6分鐘正則表達式是定義文本中搜索模式的特殊字符序列。“re.findall()”是Python中最基本的正則表達式函數之一,提取字符串表達式的開頭。本文將用這個函數告訴你,YouTube視頻標題與播放量之間的關係。
下面開始吧!
首先,導入python正則表達式模塊“re”:
<code>import re/<code>
假設有以下字符串:
<code>test_string1= 'Python is Amazing!'/<code>
可將表達式r“^\w+”與字符串一併傳遞至“re.findall”,這將返回輸入字符串的開頭:
<code>regex_1 =re.findall(r"^\w+",test_string1) print(regex_1)/<code>
在表達式r“^\w+”中,字符“^”對應字符串開頭,而“\w+”查找字符串中的字母數字字符。
如果去掉“^”,會得到:
<code>regex_1 =re.findall(r"\w+",test_string1) print(regex_1)/<code>
試提取另一個字符串示例的開頭:
<code>test_string2= 'Java is Amazing!'/<code>
現在,應用“re.findall()”查找該字符串的第一個單詞:
<code>regex_2 =re.findall(r"^\w+",test_string2) print(regex_2)/<code>
接下來,考慮一個更實際的場景。假設有一個YouTube視頻標題列表和相應的YouTube觀看次數。我們可能對分析視頻標題的第一個單詞和相應視頻觀看次數之間的關係感興趣。考慮以下標題/觀看次數元組列表:
<code>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)]/<code>
可以通過以下方式找到每個標題的第一個單詞:
<code>for titlein youtube_titles: print(re.findall(r"^\w+",title[0])[0])/<code>
可以將這些值添加到列表中:
<code>first_words= [] for title in youtube_titles: first_words.append(re.findall(r"^\w+",title[0])[0]) print(first_words)/<code>
還可以將觀看次數附加到列表中:
<code>first_words= [] views = [] for title in youtube_titles: first_words.append(re.findall(r"^\w+",title[0])[0]) views.append(title[1])/<code>
然後,可以創建視頻首字值和視頻觀看次數的數據框:
<code>importpandas as pd df = pd.DataFrame({'first_words': first_words, 'views':views}) print(df)/<code>
之後可以對每個標題首詞進行分組,並計算每個標題首詞的平均觀看次數:
<code>df =df.groupby('first_words')['views'].mean() print(df)/<code>
按降序方式對這些值進行排序:
<code>df =df.groupby('first_words')['views'].mean().sort_values(ascending = False) print(df)/<code>
假設這些結果來自一個足夠大的數據集(比如有數千個標題和觀看次數),這種類型的分析可以幫助我們選擇最佳的YouTube視頻標題。
本文討論瞭如何使用python正則表達式模塊中的“re.findall()”函數。為提取每個字符串的第一個單詞,筆者將該函數應用於兩個簡單的字符串。然後,考慮了一個實際用例,使用該函數提取YouTube視頻標題的第一個單詞,並計算第一個單詞對應的平均觀看次數。
10萬+的標題,或許就是這麼來的。
留言點贊關注
我們一起分享AI學習與發展的乾貨
如轉載,請後臺留言,遵守轉載規範