![](/img/trans.png)
[英]Using Python regex find words starting and ending with specific letters
[英]Python - find words starting and ending with vowel in dataframe column
我試圖在dataframe
列中找到以元音開頭和結尾的單詞。
我找不到 (1) 找到所有以元音開頭的單詞的regex
方法。 我只能找到以某個元音開頭的單詞。
這是我使用的code
:-
# import the CSV file
sales_data = pd.read_csv ("data/sales-data.csv")
#Words starting with 'A'. This works
Vowels1 = sales_data[sales_data['CUSTOMERNAME'].str.startswith('A')]
#Words starting with vowel. This doesn't work. Why?
Vowels2 = sales_data[sales_data['CUSTOMERNAME'].str.startswith(r'[aeiouAEIOU]')]
如何添加以元音開始和結束(同時)的條件?
#This should work, but it doesn't.
Vowels3 = sales_data[sales_data['CUSTOMERNAME'].str.startswith(r'^[aeiou].*[aeiou]$')]
The message I get for Vowels2 and Vowels3 is:
Empty DataFrame
Columns: [ORDERID, ORDERPRICE, ORDERDATE, STATUS, PRODUCTLINE, PRODUCTCODE, CUSTOMERNAME, CITY, COUNTRY]
Index: []
謝謝
你可以在這里使用str.contains
:
Vowels3 = sales_data[sales_data['CUSTOMERNAME'].str.contains(r'^[aeiou].*[aeiou]\.?$', flags=re.IGNORECASE)]
Startswith 和 Endswith 接受元組,因此您可以使用它們:
vowels = ('a','e','i','o','u','A','E','I','O','U')
if myword.startswith(vowels) and myword.endswith(vowels):
print("Yes")
因為您只對第一個和最后一個字母感興趣,所以您不需要正則regexp
開銷,甚至不需要查找序列的startwith
。
相反,您可以將 lambda lam
apply
列:
v = ('a','e','i','o','u','A','E','I','O','U')
lam = lambda word: word[0] in v and word[-1] in v
請注意這里不處理空字符串的情況
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.