您最好的选择可能是使用unicodedata模块。该解决方案有点占用资源,因为它将检查字符串中每个字符的 unicode 名称。
import unicodedata
def compute_ratio(input_str):
'''
This function will return the ratio between the number of latin letter and other letters.
'''
num_latin = 0
input_str = "".join(input_str.split()) # Remove whitespaces.
for char in input_str:
try:
if unicodedata.name(unicode(char))[:5] == "LATIN":
num_latin += 1
#end if
except UnicodeDecodeError:
pass
#end try
#end for
return (num_latin*1.0)/len(input_str)
这是您输入数据的使用示例。saved_Output 是一个包含所有有效行的数组。
>>> lines = '''She wants to ride my BMW the go for a ride in my BMW lol http://t.co/FeoNg48AQZ
RT @YuaElena: Бабушка лаÑково говорит 5-летнему Тёмочке: - Смотри, Темик, вон едет "би-би". - Бог Ñ Ñ‚Ð¾Ð±Ð¾Ð¹, бабка, Ñто-ж BMW 335xi 4x4.'''
>>> saved_Output = []
>>> for line in lines.split('\n'):
if compute_ratio(line) > 0.95:
saved_Output.append(line)
#end if
#end for
>>> "\n".join(saved_Output)
''
>>> compute_ratio('She wants to ride my BMW the go for a ride in my BMW lol http://t.co/FeoNg48AQZ')
0.890625
>>> # A ratio of 0.95 seems too high even for your first line.
>>> compute_ratio('this is a long string')
0.8095238095238095
>>> compute_ratio(u"c'est une longue cha\xeene")
0.8260869565217391