Decode the string to Unicode. Assuming it's UTF-8-encoded:
str.decode("utf-8")Call the
replacemethod and be sure to pass it a Unicode string as its first argument:str.decode("utf-8").replace(u"\u2022", "*")Encode back to UTF-8, if needed:
str.decode("utf-8").replace(u"\u2022", "*").encode("utf-8")
(Fortunately, Python 3 puts a stop to this mess. Step 3 should really only be performed just prior to I/O. Also, mind you that calling a string str shadows the built-in type str.)
Decode the string to Unicode. Assuming it's UTF-8-encoded:
str.decode("utf-8")Call the
replacemethod and be sure to pass it a Unicode string as its first argument:str.decode("utf-8").replace(u"\u2022", "*")Encode back to UTF-8, if needed:
str.decode("utf-8").replace(u"\u2022", "*").encode("utf-8")
(Fortunately, Python 3 puts a stop to this mess. Step 3 should really only be performed just prior to I/O. Also, mind you that calling a string str shadows the built-in type str.)
Encode string as unicode.
>>> special = u"\u2022"
>>> abc = u'ABC•def'
>>> abc.replace(special,'X')
u'ABCXdef'
Replacing special characters in highlighted text
python - replace special characters using unicode - Stack Overflow
ascii - Search and replace unicode character codes with actual characters - Vi and Vim Stack Exchange
php - Replace unicode formatted special characters - Stack Overflow
I have a selected text and am trying to replace all `\u00a0` special characters in it with an empty space. Is this possible to do with a simple command without resorting to writing my own implementation (something like `:%s/\%u00a0/ /g` in vim). So far i have tried `replace-string`, `replace-regexp` and `query-replace`. Any attempt says that there were 0 occurrences.
You can iterate while there are " in the string and in every iteration replace one pair of quotes:
zitat = 'Laut Durkheim ist ein "soziologischer Tatbestand jede mehr oder weniger [...] unabhängiges Eigenleben besitzt"'
print(f"Before replace: {zitat}")
while "\"" in zitat:
zitat = zitat.replace("\"", "\u201e", 1)
zitat = zitat.replace("\"", "\u201c", 1)
print(f"After replace: {zitat}")
The 1 as third argument in replace() is important to replace only the first ocurrence of the ". This should give a correct output for any string with an even number of ".
Output:
Before replace: Laut Durkheim ist ein "soziologischer Tatbestand jede mehr oder weniger [...] unabhängiges Eigenleben besitzt"
After replace: Laut Durkheim ist ein „soziologischer Tatbestand jede mehr oder weniger [...] unabhängiges Eigenleben besitzt“
I guess you are looking for this
re.sub(r'"', u"\u201E", zitat)
or the more appropriate
s = 'Laut Durkheim ist ein "soziologischer Tatbestand jede mehr oder weniger [...] unabhängiges Eigenleben besitzt"'
# substitute the opening quote
output = re.sub('\B"', u"\u201C", s)
# substitute the closing quote as well
output = re.sub('"\B', u"\u201D", output)
>>> output
'Laut Durkheim ist ein “soziologischer Tatbestand jede mehr oder weniger [...] unabhängiges Eigenleben besitzt”'
which gives
'Laut Durkheim ist ein “soziologischer Tatbestand jede mehr oder weniger [...] unabhängiges Eigenleben besitzt”'
I believe the problem is that Vim not opening the file using the right encoding. Your file is in encoding cp1252 but Vim doesn't detect it and guess utf-8.
I would propose to open the file with the ++enc=cp1252 flag.
:e ++enc=cp1252 filepath
To improve the way Vim guess the encoding you can add the following lines (Vim would first try to open as cp1252 and then as utf-8):
:set fileencodings=cp1252,utf-8
I would propose you:
:s/\([\x80-\xFF]\)/\='0x'.printf('%02x', char2nr(submatch(1)))/g
I wonder how do I search and replace unicode character xE5" with æ
Note that æ is actually Unicode 00E6 not 00E5.
Search and replace is not the right way to get the correct characters displayed.
<?xml version="1.0" encoding="utf-8"?>
The above states the encoding is utf-8 but the file is actually encoded as ANSI.
You need to convert the file correctly to UTF-8, as follows:
Open Testfile.xlf
File looks like:

Unicode is incorrectly displayed.
Menu > Encoding > Select Encode in ANSI

File looks like:

Unicode is correctly displayed.
Select all file contents (ctrl+a)
Menu > Encoding > Select Convert to UTF-8

Save the File (ctrl+s)
Close and reopen.
File is now correctly encoded as UTF-8 and Unicode characters display correctly.
How can you see the file is actually ANSI?
The cygwin file utility shows this (before and after conversion):
DavidPostill@Hal /f/test
$ file -i Testfile*.xlf
Testfile.xlf: application/xml; charset=iso-8859-1
TestfileConverted.xlf: application/xml; charset=utf-8
If you want to remove UTF-8/unicode chars entirely, click Encoding in NPP and do the following steps, in order:
- Select Encode in UTF-8 (if it's currently in ANSI)
- Select Convert to ANSI (also under encoding)
- Save file
When I do that, all the UTF-8/unicode chars go away.
I use a javascript bookmarklet for typing unicode symbols at math.stackexchange.com. Mathjax renders most unicode the same as the corresponding latex macros. For example $ℝ$ and $\mathbb{R}$ give the same result. I like the way tex code stays more compact and readable with unicode symbols.
I think this code is able to do what you want. I like to use not too many keystrokes, so instead of \alpha I use \a to produce α. You can modify this script to your own needs, and then convert it to a bookmarklet, using this website for example: http://jasonmillerdesign.com/Free_Stuff/Instant_Bookmarklet_Converter
If you want to use this script on a website without jquery, then you first need to run this bookmarklet: http://www.learningjquery.com/2006/12/jquerify-bookmarklet/
jQuery.fn.autocorrect = function(options)
{
if ("text" != jQuery(this).attr("type") && !jQuery(this).is("textarea"))
{
return;
}
var defaults = {
corrections: {
a: "α",
b: "β",
c: "γ",
d: "δ",
e: "ϵ",
emp : "∅",
f: "\\frac{}{}",
in : "∈",
s: "σ",
t: "\\text{}",
tau : "τ",
th : "θ",
p: "π",
pm : "±",
o : "ω",
O : "Ω",
r : "ρ",
A : "∀",
E : "∃",
R: "ℝ",
C: "ℂ",
H: "ℍ",
N: "ℕ",
Q: "ℚ",
Z: "ℤ",
int: "\\int_{}^{}",
inf : "∞",
sum : "\\sum_{}^{}",
"-1": "^{-1}",
ph: "ϕ",
ch: "χ",
ps: "ψ",
leq : "≥",
xi : "ξ",
geq : "≤",
"/=" : "≠",
"==" : "≡",
"<" : "\\langle {} \\rangle",
"->" : "→",
"=>" : "⇒",
"<=" : "⇐",
"<>" : "⇔",
"sq" : "\\sqrt{}"
}
};
if (options && options.corrections)
{
options.corrections = jQuery.extend(defaults.corrections, options.corrections);
}
var opts = jQuery.extend(defaults, options);
getCaretPosition = function(oField)
{
var iCaretPos = 0;
if (document.selection)
{
var oSel = document.selection.createRange();
oSel.moveStart("character", 0 - oField.value.length);
iCaretPos = oSel.text.length;
}
else if (oField.selectionStart || oField.selectionStart == "0")
{
iCaretPos = oField.selectionStart;
}
return (iCaretPos);
}
function setCaretPosition (oField, iCaretPos)
{
if (document.selection)
{
var oSel = document.selection.createRange();
oSel.moveStart("character", 0 - oField.value.length);
oSel.moveStart("character", iCaretPos);
oSel.moveEnd("character", 0);
}
else if (oField.selectionStart || oField.selectionStart == "0")
{
oField.selectionStart = iCaretPos;
oField.selectionEnd = iCaretPos;
}
}
this.keyup(function(e)
{
if (32 != e.keyCode)
{
return;
}
var caretPosition = (getCaretPosition(this) - 1);
if (1 > caretPosition)
{
return;
}
var valueOfField = this.value;
var stringUptoCaretPosition = (valueOfField).substr(0, caretPosition);
if (" " == stringUptoCaretPosition.charAt(caretPosition - 1))
{
return;
}
var beginIndex = stringUptoCaretPosition.lastIndexOf('\\');
if (beginIndex < stringUptoCaretPosition.lastIndexOf(' '))
{
return;
}
var stringToSearch = stringUptoCaretPosition.substring(beginIndex+1);
var stringNotToSearch = stringUptoCaretPosition.substring(0, beginIndex);
if (!opts.corrections[stringToSearch])
{
return;
}
var stringToReplace = opts.corrections[stringToSearch];
stringUptoCaretPosition = stringNotToSearch+ stringToReplace;
var stringFromCaretPositionUptoEnd = (valueOfField).substr(caretPosition+1);
this.value = (stringUptoCaretPosition + stringFromCaretPositionUptoEnd);
if (stringToReplace.indexOf("{}")!=-1 )
{
setCaretPosition(this, stringUptoCaretPosition.indexOf("{}")+1);
}
else { setCaretPosition(this, stringUptoCaretPosition.length);}
});
};
$(document).ready(function()
{
$("textarea").autocorrect();
});
Autohotkey-script for converting LaTeX-like input to unicode characters
"Ctrl+Alt+Shift+U" toggles it on and off (look at the bottom right icon to see it's in suspense mode (icon S) of active mode (icon H).
Test: αβΓ∞¹₂ℝ
Hi Reddit,
I am trying to create a script that creates ad users automatically, however, in my country we have special characters in our name like åäö and such, and i want them replaced with their equivalent a, and o. How am i to proceed with this so the script does it automatically? it is only required for the logins, not the display name and such. My script is set up like this:
$firstname (asks for input)
$surname (asks for input)
$username = $firstname+'.'+$surname ($username is the firstname.lastname@domain.com)
Word plays internal tricks with Unicode symbols, and doesn't report the true character values. To make successful replacements, use the macros in the article https://wordmvp.com/FAQs/MacrosVBA/FindReplaceSymbols.htm.
Hi Jay,
Thank you very much - the macros in the article worked just great!
This was the first time I ever dabbled with VBA in Word, and this worked almost first time. (I do have quite a lot of experience writing VBA macros in Excel, but never in Word.)
Something I learned from using these macros for my specific case - to find and replace all the ?-in-a-rectangles with a regular double quote - is that, in Word t,here is a difference between an opening double quote mark and a closing double quote mark.
At first I highlighted a double quote mark in my document (by chance, a closing one), and used the code that the first macro returned to replace ALL of the ?-in-a-rectangles. This caused the Word spelling & grammar checker to complain that, for all the replaced opening quotes, the adjacent space should go after the quote character. This made me realize that the opening & closing quotes had different codes, though in my document they looked the same. Only when I enlarged the font, was a difference between them discernable.
Also, only the opening ?-in-a-rectangle was replaced by the closing ". This made me very suspicious, so I used the first macro to display the code of the closing ?-in-a-rectangle - it also was different from the opening character code, which is what I'd used in the second macro.
So I undid all the replacements, and ran the second macro again, twice, each time with the corresponding codes for the opening & closing characters. (8220 --> 147, 8221 --> 148, all (normal text) font)
This time the result was perfect.
many thanks!.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unicodedata
text = u'Cześć'
print unicodedata.normalize('NFD', text).encode('ascii', 'ignore')
The package unidecode worked best for me:
from unidecode import unidecode
text = "Björn, Łukasz and Σωκράτης."
print(unidecode(text))
# ==> Bjorn, Lukasz and Sokrates.
You might need to install the package:
pip install unidecode
The above solution is easier and more robust than encoding (and decoding) the output of unicodedata.normalize(), as suggested by other answers.
# This doesn't work as expected:
ret = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore')
print(ret)
# ==> b'Bjorn, ukasz and .'
# Besides not supporting all characters, the returned value is a
# bytes object in python3. To yield a str type:
ret = ret.decode("utf8") # (not required in python2)
That depends on what you mean. If you just want to get rid of them, do this:
(Update: Apparently you want to keep digits as well, use the second lines in that case)
String alphaOnly = input.replaceAll("[^a-zA-Z]+","");
String alphaAndDigits = input.replaceAll("[^a-zA-Z0-9]+","");
or the equivalent:
String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");
(All of these can be significantly improved by precompiling the regex pattern and storing it in a constant)
Or, with Guava:
private static final CharMatcher ALNUM =
CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z'))
.or(CharMatcher.inRange('0', '9')).precomputed();
// ...
String alphaAndDigits = ALNUM.retainFrom(input);
But if you want to turn accented characters into something sensible that's still ascii, look at these questions:
- Converting Java String to ASCII
- Java change áéőűú to aeouu
- ń ǹ ň ñ ṅ ņ ṇ ṋ ṉ ̈ ɲ ƞ ᶇ ɳ ȵ --> n or Remove diacritical marks from unicode chars
I am using this.
s = s.replaceAll("\\W", "");
It replace all special characters from string.
Here
\w : A word character, short for [a-zA-Z_0-9]
\W : A non-word character