在Python unicoded string中查找并替换这两种引号样式

2024-09-29 21:59:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在Python中的字符串上替换用引号样式(“…”和“…”)标记的字符串。在

我已经写了一个正则表达式来代替标准引用

print re.sub(r'\"(.+?)\"', r'<em>"\1"</em>', self.title)

当我试图为文学作品做这件事时(?)它不能取代任何东西。在

^{pr2}$

事实上,正如我现在所掌握的,我甚至不能进行条件查询:

quote_list = ['“', '”']

if all(character in self.title for character in quote_list):
    print "It has literary quotes"
    print re.sub(r'\“(.+?)\”', r'<em>“\1”</em>', self.title)
print re.sub(r'\"(.+?)\"', r'<em>"\1"</em>', self.title)

编辑:进一步的上下文:它是一个对象

class Entry(models.Model):
    title = models.CharField(max_length=200)

def render_title(self):
    """
    This function wraps italics around quotation marks
    """
    quote_list = ['“', '”']

    if all(character in self.title for character in quote_list):
        print "It has literary quotes"
        return re.sub(r'\“(.+?)\”', r'<em>“\1”</em>', self.title)
    return re.sub(r'\"(.+?)\"', r'<em>"\1"</em>', self.title)

我不太精通regex命令。我做错什么了?在

离问题更近一步!这取决于我处理的是单子串。我还不知道该怎么解决这个问题。感谢任何帮助!在

>>> title = u"sdsfgsdfgsdgfsdgs “ asd” asd"
>>> print re.sub(r'\“(.+?)\”', r'<em>“\1”</em>', title)
sdsfgsdfgsdgfsdgs “ asd” asd
>>> title = "sdsfgsdfgsdgfsdgs “ asd” asd"
>>> print re.sub(r'\“(.+?)\”', r'<em>“\1”</em>', title)
sdsfgsdfgsdgfsdgs <em>“ asd”</em> asd

Tags: 字符串inselfreforiftitleall
2条回答
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
quote_list = ['“', '”']
title = "“...”"

if all(character in title for character in quote_list):
    print "It has literary quotes"
    print re.sub(r'\“(.+?)\”', r'<em>“\1”</em>', title)
  1. 请检查您的编码是否支持您正在使用的字符。我在这里使用的是utf-8,它支持您使用的引号,一切都很好。在
  2. 你的if条件可能根本不为真,请检查条件是否都为真。all当每个元素为Truthy时返回true

在比较或使用regexpression时,请确保编码格式是相同的。支持对unicode字符串使用unicode regexp模式

^{pr2}$

我终于找到了答案。在按@interjay的建议打印变量后,我发现字符串是unicoded。在

将它与一个简单的字符串进行比较不起作用,所以我删除了条件,并使用这个answer简单地生成一个unicode转义regex字符串来处理简单和“文学”引号。在

title = re.sub(ur'\“(.+?)\”', ur'“<em>\1</em>”', self.title)  # notice the ur
title = re.sub(ur'\"(.+?)\"', ur'"<em>\1</em>"', title)

我在这里看到了一条评论(不幸的是现在被删除了)如何把上面的两个句子合并成一个句子,但是现在它起作用了。在

非常感谢你的帮助!在

相关问题 更多 >

    热门问题