首页 文章

Python 3中不会删除特殊的Unicode字符

提问于
浏览
0

我有一个包含单词的 keys 列表 . 当我发出这个命令:

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?

我使用Beautiful Soup从Google趋势中删除了此内容并从 get_text() 检索了文本 . 同样在Google趋势页面的页面来源中,单词列出如下:

enter image description here
当我直接从页面源粘贴文本时,粘贴的文本没有这些不寻常的符号 .

1 回答

  • 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']
    >>>
    

    试过你的一个方法,它对我有用:

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

相关问题