Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
以结尾为的python单词中的字符串比较_Python - Fatal编程技术网

以结尾为的python单词中的字符串比较

以结尾为的python单词中的字符串比较,python,Python,我有一组词如下: ['Hey, how are you?\n','My name is Mathews.\n','I hate vegetables\n','French fries came out soggy\n'] # 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 在上

我有一组词如下:

['Hey, how are you?\n','My name is Mathews.\n','I hate vegetables\n','French fries came out soggy\n']
# 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
在上面的句子中,我需要识别所有以
或“gy”结尾的句子。然后打印最后一个单词

我的做法如下:

['Hey, how are you?\n','My name is Mathews.\n','I hate vegetables\n','French fries came out soggy\n']
# 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
我得到的结果是:

嘿,你好吗

我叫马修斯

我讨厌蔬菜

炸薯条出来时湿漉漉的

预期结果是:

你呢

马修斯

湿漉漉的

使用方法

输出:

you?
Mathews.
soggy
与元组一起使用

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
你很接近

您只需转义模式中的特殊字符(
):

re.search(r'(\?|\.|gy)$', w)

您是想打印句子还是句子末尾的单词?只有单词,而不是句子顺便说一下,您没有一组单词,您有一个字符串列表。您不需要调用
strip()
,因为
split()
没有分隔符可以修剪前导和尾随空格。@false:Fixed。谢谢。:)BTWm什么是
r
?@sharonHwk,带前导
r
的字符串称为原始字符串。原始字符串转义反斜杠。@sharonHwk这是一个原始字符串。文档以打开。