簡體   English   中英

如何用交替字符'“'和'”'(python)替換字符串中隨機重復的字符'"'?

[英]How to replace character ' " ' randomly repeated in a string with alternating characters ' “ ' and ' ” ' (python)?

我試圖用一組彎曲的開引號和閉引號(“和”)替換給定字符串中的任何普通直引號(“)。這意味着第一個,第三個等“將被替換為”,第二個,第四個等“s 將被替換為”。

我已經嘗試找到第一個引號的索引,創建一個拼接,並將該拼接中的所有“”替換為“。我通過從這個新引號索引 + 1 到末尾創建一個拼接並替換所有“ 和 ”。 問題是,我不能確定提供的字符串中 "s 的長度或數量,因此需要找出一種方法來循環這樣的某種系統。

這僅適用於正確轉換帶有 2 個引號的字符串:

 def convert_quotes(text): '''(str) -> str Convert the straight quotation mark into open/close quotations. >>> convert_quotes('"Hello"') '“Hello”' >>> convert_quotes('"Hi" and "Hello"') '“Hi” and “Hello”' >>> convert_quotes('"') '“' >>> convert_quotes('"""') '“”“' >>> convert_quotes('" "o" "i" "') '“ ”o“ ”i“ ”' ''' find=text.find('"') if find:= -1: for i in text: #first convert first found " to “ text1 = text[.find+1] replace1=text1,replace('"':'“') text2 = text[find+1.] replace2=text2,replace('"','”') text=replace1+replace2 return text

正如在我的文檔字符串中看到的,'"Hello" 應該變成 "Hello",但是 '" "o" "i" "' 應該變成 " 'o" 'i“ ”。

您可能希望收集所有帶引號的位置,然后相應地更改字符。 這需要一個中間字符列表(下面的s_list ):

import re

s = '"Hi" and "Hello"'
s_list = list(s)

quote_position = [p.start() for p in re.finditer('"', s)]

for po, pc in zip(quote_position[::2], quote_position[1::2]):
    s_list[po] = '“'
    s_list[pc] = '”'

s = "".join(s_list)

您可以使用 re.sub function。 我將使用括號以提高可讀性,只需將它們替換為您的引號即可。

import re

s = """
sdffsd"fsdfsdfdsf fdsf<s" fgdgdfgdf " gfdgdfgd" gdfgdfgdf"
bla re bla
dfsfds " fdsfsdf " fsdfsd "
and the final odd " is here
"""

def func(match): # function for to be called for each sub() step
    return("(" + match.group()[1:-1] + ")")

rex  = re.compile(r'"[^"]*"') # regular expression for a quoted string.

result = rex.sub(func, s) # substitute each match in s with func(match)
result = result.replace('"', '(')  # take care of last remaining " if existing
print(result)

output 將是:

sdffsd(fsdfsdfdsf fdsf<s) fgdgdfgdf ( gfdgdfgd) gdfgdfgdf(
bla re bla
dfsfds ) fdsfsdf ( fsdfsd )
and the final odd ( is here

不使用 re 模塊的第二種解決方案:

s = """
sdffsd"fsdfsdfdsf fdsf<s" fgdgdfgdf " gfdgdfgd" gdfgdfgdf"
bla re bla
dfsfds " fdsfsdf " fsdfsd "
and the final odd " is here
"""

while True:
    if not '"' in s:
        break
    s = s.replace('"', '(', 1)
    s = s.replace('"', ')', 1)

print(s)

我沒有做任何努力使其高效。 重點是簡單。

暫無
暫無

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

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