【问题标题】:How to convert straight quotes to curly quotes in python?如何在python中将直引号转换为弯引号?
【发布时间】:2022-02-22 20:44:47
【问题描述】:

我必须将所有直引号 (") 替换为大引号 ()

我使用s.replace 将所有直引号替换为弯引号,但是它们都在同一个方向。我不知道如何让花引号在一个单词的前面朝一个方向,而在结尾的方向相反。

例如:'" "o" "i" "' 必须转换为 '“ “o” “i” ”'

【问题讨论】:

  • 理论上,你无法说出来。 '""""' 应该是 '“”“”' 还是 '““””'? (开-关-开-关 vs 开-开-关-关)
  • 对不起,我弄错了

标签: python python-3.x double-quotes converters


【解决方案1】:

你可以试试这个(text 是你的字符串):

for i in range(text.count('"')/2+1) :
    text = text.replace( '"', 'open-quote', 1)
    text = text.replace( '"', 'close-quote', 1)

它们都将被替换。

open-quoteclose-quote 用于方便阅读,请替换为您需要的实际引号字符。

【讨论】:

  • @Jab 现在好点了吗?
【解决方案2】:

这似乎工作得很好:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import re

def convert_to_curly(string):
    """convert straight quotes to curly ones"""
    string = re.sub(r'\b"',r'”',string)   # closing double on word    
    string = re.sub(r'"\b',r'“',string)   # opening double on word
    string = re.sub(r'\b\'',r'’',string)  # closing single on word
    string = re.sub(r'\'\b',r'‘',string)  # opening single on word

    string = re.sub(r'([^\w\d\s:])"',r'\1”',string)  # closing double on punctuation
    string = re.sub(r'([^\w\d\s:])\'',r'\1’',string) # closing single on punctuation

    string = re.sub(r'\S\'\S',r'’',string)   # apostrophe can be virtually anywhere

    # FIXME: what about single and double quotes not next to word or punctuation? Pairs?

    return(string)

【讨论】:

    【解决方案3】:

    您可以使用re 并查找成对的引号并替换它们。

    >>> s = "\" \"o\" \"i\" \""
    >>> s
    '" "o" "i" "'
    >>> re.sub(r'(\")(.?)(\")', '“\g<2>”', s)
    '“ ”o“ ”i“ ”'
    

    【讨论】:

      猜你喜欢
      • 2011-01-13
      • 2013-05-28
      • 2017-03-11
      • 1970-01-01
      • 2012-01-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      相关资源
      最近更新 更多