技术问询:如何替换特殊字符及将学术引用中的页码标识"S."替换为冒号":"
Hey Celina! Let's sort out those citation formatting and special character replacement issues you're dealing with. Your current approach is hitting snags because global replacements are too broad—let's fix that with targeted solutions.
1. Precisely Replace "S. " in Citations with ": "
The core problem with your original code is that it replaces all instances of "S" or ".", which messes up parts of the text you want to keep. Instead, use regular expressions to target only the "S. " inside citation parentheses:
import re # Your original string x = 'Laut Durkheim ist ein "soziologischer Tatbestand [...] individuellen Äußerungen unabhängiges Eigenleben besitzt" (Durkheim 1984, S. 115).' # Target only ", S. " in the citation and replace with ", : " x = re.sub(r', S\. ', ', : ', x)
Here's what this regex does:
r', S\. 'matches the exact pattern: comma + space + "S" + escaped dot (since dots are special in regex) + space- It only replaces this specific pattern, so other "S" characters or dots in your text stay untouched.
2. Replace HTML Escaped Quotes (") with Actual Double Quotes
To convert the escaped " back to regular double quotes, a simple string replacement works perfectly:
x = x.replace('"', '"')
Full Working Code
Combine both steps to get your desired output:
import re x = 'Laut Durkheim ist ein "soziologischer Tatbestand [...] individuellen Äußerungen unabhängiges Eigenleben besitzt" (Durkheim 1984, S. 115).' # Step 1: Fix citation page marker x = re.sub(r', S\. ', ', : ', x) # Step 2: Restore double quotes x = x.replace('"', '"') print(x)
When you run this, you'll get exactly the result you want:
Laut Durkheim ist ein "soziologischer Tatbestand [...] individuellen Äußerungen unabhängiges Eigenleben besitzt" (Durkheim 1984: 115).
Why Your Original Code Failed
x.replace('S', ''): This deletes every "S" in the string, not just the one in the citation. It also leaves a stray dot where "S." used to be.x.replace('.', ':'): This replaces all dots—including those in[...]and the final sentence-ending dot—with colons, which breaks the rest of your text.
内容的提问来源于stack exchange,提问作者Celina

