ASCII中特殊字符的记帐

人气:774 发布:2022-10-16 标签: python utf-8 ascii data-science

问题描述

我正在尝试对正在处理的问题的数据集中的非英语应用进行过滤操作。

如何从数据集中删除非英语应用程序?最初的方法是检查字符串是否可以仅使用ASCII字符进行编码。如果该字符串不能仅使用ASCII字符进行编码,则该字符串包含来自其他字母表或特殊字符的字符。

在一些玩具示例上测试此方法会产生以下结果:

def is_english(app_name):
try:
    app_name.encode(encoding='utf-8').decode('ascii')
except UnicodeDecodeError:
    return False
else:
    return True

print(is_english('Instagram'))
print(is_english('爱奇艺PPS -《欢乐颂2》电视剧热播'))
print(is_english('Docs To Go™ Free Office Suite'))
print(is_english('Instachat '))

很明显,最初的做法有一个问题,即‘Docs to Go™免费办公套件’和‘Instachat’这两个英文应用程序都被识别为非英语应用程序,因为它们有特殊字符(即‘™’和‘’)。

有关如何允许使用特殊字符(如"™"、表情符号等)的任何建议?

推荐答案

您可以定义一个函数来计算有多少字符可能是英文字符,并返回某个阈值以上的True。仍然不是100%完美的(例如,想一想共享相同字母的德语单词,如Tastatur[键盘]),但可能是一个开始:

import re
def is_probably_english(app_name, threshold=0.9):
    rx = re.compile(r'[-a-zA-Z0-9_ ]')
    ascii = [char for char in app_name if rx.search(char)]
    quotient = len(ascii) / len(app_name)
    passed = True if quotient >= threshold else False
    return passed, quotient


print(is_probably_english('Instagram'))
print(is_probably_english('爱奇艺PPS -《欢乐颂2》电视剧热播'))
print(is_probably_english('Docs To Go™ Free Office Suite'))
print(is_probably_english('Instachat '))

这会产生

(True, 1.0)
(False, 0.3157894736842105)
(True, 0.9655172413793104)
(True, 0.9090909090909091)

703