我希望找到以ing结尾的单词并打印它们,我当前的代码打印出而不是单词。
#match all words ending in ing
import re
expression = input("please enter an expression: ")
print(re.findall(r'\b\w+(ing\b)', expression))
所以如果我们输入一个表达式:sharing all the information you are hearing
我希望['sharing', 'hearing']
打印出来
相反,我打印出['ing', 'ing']
有没有快速解决方法?
答案 0 :(得分:10)
您的捕获分组错误请尝试以下操作:
>>> s="sharing all the information you are hearing"
>>> re.findall(r'\b(\w+ing)\b',s)
['sharing', 'hearing']
您还可以在列表解析中使用str.endswith
方法:
>>> [w for w in s.split() if w.endswith('ing')]
['sharing', 'hearing']
答案 1 :(得分:4)
圆括号“捕获”字符串中的文本。您有'(ing\b)'
,因此只会捕获ing
。移动左括号,使其包含您想要的整个字符串:r'\b(\w+ing)\b'
。看看是否有帮助。
答案 2 :(得分:1)
尝试一下。会的!
import json,tempfile
config = {"A":[1,2], "B":"Super"}
tfile = tempfile.NamedTemporaryFile(mode="w+")
json.dump(config, tfile)
tfile.flush()
print(tfile.name)
答案 3 :(得分:0)
sentence = 'sharing all the information you are hearing'
# spit so we have list of words from sentence
words = sentence.split(' ')
ending_with('ing',words)
def ending_with(ending, words):
# loop through words
for word in words:
# if word has ends with ending
if word.endswith(ending):
# print
print word