When I'm processing HTML code in Python I have to use the following code because of special characters.
line = string.replace(line, """, "\"")
line = string.replace(line, "'", "'")
line = string.replace(line, "&", "&")
line = string.replace(line, "<", "<")
line = string.replace(line, ">", ">")
line = string.replace(line, "«", "<<")
line = string.replace(line, "»", ">>")
line = string.replace(line, "'", "'")
line = string.replace(line, "“", "\"")
line = string.replace(line, "”", "\"")
line = string.replace(line, "‘", "\'")
line = string.replace(line, "’", "\'")
line = string.replace(line, "■", "")
line = string.replace(line, "•", "-")
It seems there will be much more such special characters I have to replace. Do you know how to make this code more elegant?
thank you
REPLACEMENTS = [
(""", "\""),
("'", "'"),
...
]
for entity, replacement in REPLACEMENTS:
line = line.replace(entity, replacement)
Note that string.replace is simply available as a method on str/unicode objects.
Better yet, check out this question!
The title of your question asks something different, though: optimization, i.e. making it run faster. That's a completely different problem, and will require more work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With