【问题标题】:Removing Non Unicode characters from a file从文件中删除非 Unicode 字符
【发布时间】:2018-09-03 04:12:19
【问题描述】:

我知道这是一个重复的问题,但到目前为止我真的很努力地尝试了所有的解决方案。任何人都可以帮助如何摆脱文件中的 \xc3\xa2\xc2\x84\xc2\xa2 等字符吗?

我目前要清理的文件内容是: b'烤洋葱蘸酱',"b""['2磅大黄洋葱,切成薄片','3个大葱,切成薄片','4枝百里香','1/4杯橄榄油','犹太盐和现磨黑胡椒粉”、“1 杯白葡萄酒”、“2 汤匙香槟醋”、“2 杯酸奶油”、“1/2 杯切碎的新鲜韭菜”、“1/4 杯纯希腊酸奶”、“应有尽有”调味料和百里香装饰', '鳕鱼角波浪\xc3\xa2\xc2\x84\xc2\xa2 薯片']"""

我尝试过使用 re.sub('[^\x00-\x7F]+',' ',whatevertext) 但似乎无处可去。我怀疑这里的 \ 没有被视为特殊字符。

【问题讨论】:

    标签: python-2.7 ascii non-ascii-characters python-unicode non-unicode


    【解决方案1】:

    你可以这样做:

    >>> f = open("test.txt","r")
    >>> whatevertext = f.read()
    >>> print whatevertext
    b'Roasted Onion Dip',"b""['2 pounds large yellow onions, thinly sliced', '3 large shallots, thinly sliced', '4 sprigs thyme', '1/4 cup olive oil', 'Kosher salt and freshly ground black pepper', '1 cup white wine', '2 tablespoons champagne vinegar', '2 cups sour cream', '1/2 cup chopped fresh chives', '1/4 cup plain Greek yogurt', 'Everything seasoning and thyme to garnish', 'Cape Cod Waves\xc3\xa2\xc2\x84\xc2\xa2 Potato Chips for serving']"""
    
    >>> import re
    >>> result = re.sub('\\\\x[a-f|0-9]+','',whatevertext)
    >>> print result
    b'Roasted Onion Dip',"b""['2 pounds large yellow onions, thinly sliced', '3 large shallots, thinly sliced', '4 sprigs thyme', '1/4 cup olive oil', 'Kosher salt and freshly ground black pepper', '1 cup white wine', '2 tablespoons champagne vinegar', '2 cups sour cream', '1/2 cup chopped fresh chives', '1/4 cup plain Greek yogurt', 'Everything seasoning and thyme to garnish', 'Cape Cod Waves Potato Chips for serving']"""
    
    >>> 
    

    '\\x[af|0-9]+' 在这个正则表达式中,每个斜线都用斜线转义,在 x 之后,我们知道可以有 0-9 的数字或 af 的字母。

    【讨论】:

    • 超级!非常感谢!
    猜你喜欢
    • 2015-04-23
    • 2019-11-26
    • 1970-01-01
    • 2013-09-25
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 2010-12-27
    相关资源
    最近更新 更多