我有一组单词如下:
['Hey, how are you?\n','My name is Mathews.\n','I hate vegetables\n','French fries came out soggy\n']
Run Code Online (Sandbox Code Playgroud)
在上面的句子中,我需要识别以?or .或'gy' 结尾的所有句子.并打印最后一个字.
我的方法如下:
# words will contain the string i have pasted above.
word = [w for w in words if re.search('(?|.|gy)$', w)]
for i in word:
print i
Run Code Online (Sandbox Code Playgroud)
我得到的结果是:
嘿,你怎么样?
我的名字是马修斯.
我讨厌蔬菜
炸薯条湿透了
预期的结果是:
您?
马修斯.
浸水
Suk*_*lra 12
使用endswith()方法.
>>> for line in testList:
for word in line.split():
if word.endswith(('?', '.', 'gy')) :
print word
Run Code Online (Sandbox Code Playgroud)
输出:
you?
Mathews.
soggy
Run Code Online (Sandbox Code Playgroud)
使用带有元组的结尾.
lines = ['Hey, how are you?\n','My name is Mathews.\n','I hate vegetables\n','French fries came out soggy\n']
for line in lines:
for word in line.split():
if word.endswith(('?', '.', 'gy')):
print word
Run Code Online (Sandbox Code Playgroud)
正则表达式替代:
import re
lines = ['Hey, how are you?\n','My name is Mathews.\n','I hate vegetables\n','French fries came out soggy\n']
for line in lines:
for word in re.findall(r'\w+(?:\?|\.|gy\b)', line):
print word
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6656 次 |
| 最近记录: |