簡體   English   中英

如何在 python 中將直引號轉換為彎引號?

[英]How to convert straight quotes to curly quotes in python?

我必須將所有直引號替換為彎引號(“”)。

我使用 s.replace 將所有直引號替換為彎引號,但是,它們都在同一個方向。 我不知道如何在單詞前面有一個方向的彎引號,而在最后一個相反的方向。

例如: '" "o" "i" "'必須轉換為'“ “o” “i” ”'

你可以試試這個( text是你的字符串):

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

它們都將被替換。

open-quoteclose-quote用於易於閱讀,替換為您需要的實際引號字符。

您可以使用re並查找成對的引號並替換它們。

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

這似乎工作得很好:

#!/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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM