2017-07-12 66 views
0

我有一個keys列表包括單詞。當我做這個命令:特殊的Unicode字符不會在Python 3中刪除

for key in keys: 
    print(key) 

我在終端得到正常輸出。

enter image description here

但是當我打印使用print(keys)整個列表,我得到這樣的輸出:

enter image description here

我一直在使用key.replace("\u202c", '')key.replace("\\u202c", '')re.sub(u'\u202c', '', key)嘗試,但沒有解決的問題。 我也嘗試過的解決方案在這裏,但他們沒有工作之一:

Replacing a unicode character in a string in Python 3

Removing unicode \u2026 like characters in a string in python2.7

Python removing extra special unicode characters

How can I remove non-ASCII characters but leave periods and spaces using Python?

我用美麗的湯刮這從谷歌趨勢和檢索來自get_text()的文本 也在Google Tr的頁面源代碼中結束頁,字列舉如下:

enter image description here當我在這裏直接從網頁源代碼,沒有這些不尋常的符號粘貼文本粘貼文本

+0

@OferSadan我只是嘗試這樣做,得到了相同的輸出中的問題。 –

+0

生成後在列表中的每個項目上執行'sub(r'\ p {Block = General_Punctuation} +','')'。或者,您可以使用_block_的範圍'[\ u2000- \ u206F] +'。見https://www.compart.com/en/unicode/block/U+2000 – sln

+0

另請參閱https://en.wikipedia.org/wiki/General_Punctuation – sln

回答

1

您只需去掉使用strip人物。

>>> keys=['\u202cABCD', '\u202cXYZ\u202c'] 
>>> for key in keys: 
...  print(key) 
... 
ABCD 
XYZ‬ 
>>> newkeys=[key.strip('\u202c') for key in keys] 
>>> print(keys) 
['\u202cABCD', '\u202cXYZ\u202c'] 
>>> print(newkeys) 
['ABCD', 'XYZ'] 
>>> 

試過你的方法1,它的工作對我來說:

>>> keys 
['\u202cABCD', '\u202cXYZ\u202c'] 
>>> newkeys=[] 
>>> for key in keys: 
...  newkeys += [key.replace('\u202c', '')] 
... 
>>> newkeys 
['ABCD', 'XYZ'] 
>>> 
+0

這爲我工作了!關於爲什麼我之前嘗試的方法不起作用的任何見解? –

+0

@HimanshuAhuja我嘗試了1個方法,它在python3中對我有效 – ritesht93