我有一组单词如下:
['Hey, how are you?\n','My name is Mathews.\n','I hate vegetables\n','French fries came out soggy\n']
在上面的句子中,我需要识别所有以?
或.
或'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
我得到的结果是:
嘿,你好吗?我的名字是Mathews。
我讨厌蔬菜
炸薯条湿透了
预期结果是:
你?
马修斯。
潮湿
答案 0 :(得分:10)
使用endswith()
方法。
>>> for line in testList:
for word in line.split():
if word.endswith(('?', '.', 'gy')) :
print word
输出:
you?
Mathews.
soggy
答案 1 :(得分:5)
将endswith与元组一起使用。
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
正则表达式替代:
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
答案 2 :(得分:3)