Python删除csv中的非拉丁文本行

时间:2013-09-03 07:23:55

标签: python csv unicode

我有一个csv文件,其中包含字符串形式的文本。 一些文本行例如是中文或俄文。

我想要做的是使用Python来计算文本行中的unicode和ASCII字符数。 如果ASCII与Uni​​code字符的比例超过90%,我想保留该行,如果不是从csv中删除它。

这背后的想法是删除所有非拉丁语言,但保留德国变形金刚,为此我想使用比率的解决方案。

有人有想法解决这个问题吗?

非常感谢!

以下是我的csv数据的一些示例:

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.

所以你应该知道我的数据是怎样的。

2 个答案:

答案 0 :(得分:1)

拉丁语范围以\u00ff结尾,因此您所要做的就是使用正则表达式删除\u0100-\uffff范围内的字符,然后将新行长度与原始行长度进行比较。

也就是说,使用re.sub(r'[\u0100-\uffff]', "?", line)来保留该行并用?替换所有不需要的字符可能更有用。

答案 1 :(得分:0)

您最好的选择可能是使用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