Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.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_Regex - Fatal编程技术网

Python正则表达式替换以创建笑脸

Python正则表达式替换以创建笑脸,python,regex,Python,Regex,我想创建一个正则表达式字符串,用于转换此文本: Hello this is a mighty fine day today 进入 使用python re.sub oneliner是否可以做到这一点?不需要正则表达式: s = 'Hello this is a mighty fine day today' ' '.join('%s%sD'%('8' if len(w) > 1 else '', '='*(len(w)-2)) for w in s.split()) # '8===D 8==

我想创建一个正则表达式字符串,用于转换此文本:

Hello this is a mighty fine day today
进入

使用python re.sub oneliner是否可以做到这一点?

不需要正则表达式:

s = 'Hello this is a mighty fine day today'
' '.join('%s%sD'%('8' if len(w) > 1 else '', '='*(len(w)-2)) for w in s.split())
# '8===D 8==D 8D D 8====D 8==D 8=D 8===D'
编辑:已调试;)谢谢你的指针@tg

这是你的一行代码(对不起,没有正则表达式):


问题是需要一个
re.sub
1行程序,因此这里有一个执行此任务的程序:

In [1]: import re

In [2]: s = "Hello this is a mighty fine day today"
In [3]: print re.sub(r"\w+", lambda x:("8"+"="*1000)[:len(x.group())-1]+"D", s)
8===D 8==D 8D D 8====D 8==D 8=D 8===D

仅用于教育目的!8=D

根据要求,这里有一个re.sub-oneliner(为清晰起见拆分):


我认为没有任何理由像以前的解决方案那样使用正则表达式。请尝试以下方法:

def pen(string):
    return ' '.join([("%s%s%s"%('8','='*(len(word)-2),'D'))[-len(word):] \
         for word in string.split()])

它似乎比我随意选择的一个正则表达式要快得多。

不管你怎么想,这些都不是笑脸。@Chris:它们让我笑了……是的,这是可能的:
re.sub('.*','8===d8d8==d8==d8==d8==D','Hello今天天气非常好'
。对不起,无法抗拒,你可以考虑更清楚地说出你想要什么……现在他不再有两个问题了。虽然这可能会在标点符号上做一些有趣的事情……单字母的
D
在哪里?@tg:Whoops,我原来没看到。很好,你们注意到了。我会做类似于原文的:
“”。在s.split()中为w加入('8'+'='*(len(w)-2)+'d'[-len(w):]如果len(word)>1),它会为单个字母提供
8D
。在句子中的单词加入(['8%sD'”('='*(len(word)-2))。如果len(word)>1),split(“”)Woops,并没有意识到mhyfritz已经发布了一个非正则解决方案。我的比他的快,直到他改变
''。加入(…)
''。加入([…])
In [1]: import re

In [2]: s = "Hello this is a mighty fine day today"
In [3]: print re.sub(r"\w+", lambda x:("8"+"="*1000)[:len(x.group())-1]+"D", s)
8===D 8==D 8D D 8====D 8==D 8=D 8===D
import re 

print re.sub( r'\w(\w?)(\w*)', \
              lambda m: '8'*len(m.group(1)) + '='*len(m.group(2)) + 'D', \
              "Hello this is a mighty fine day today" )
def pen(string):
    return ' '.join([("%s%s%s"%('8','='*(len(word)-2),'D'))[-len(word):] \
         for word in string.split()])