用Python语言进行大数据检测

问题描述

我正在尝试对熊猫数据框中的Series对象运行语言检测。但是,我正在处理数百万行的字符串数据,并且标准的Python语言检测库langdetectlangid太慢,并且在运行数小时后仍未完成。

我将代码设置如下:

#function to detect language
def detect_language (cell):
    if len(cell) > 0:
        lan = langid.classify(cell)
    else:
        lan = "NaN"
    return lan
#language detection using langid module

df['language'] = df.apply(lambda row: detect_language(row.Series),axis = 1)

有人对如何加快我的代码速度或者是否还有另一个库提出建议吗?

解决方法

您可以使用swifter来提高df.apply()的效率。除此之外,您可能想尝试whatthelang库,该库应该比langdetect更有效。

,

将数据采样到多个随机集合中,然后使用快速文本https://fasttext.cc快速获取结果。快速高效。

import fasttext
path_to_pretrained_model = "lid.176.bin"
fmodel = fasttext.load_model(path_to_pretrained_model)
from datetime import datetime
df['language']=''
for i in df.index:
    ln_cnt = i
    result = fmodel.predict(str(df['prcsd_title'][i]))
    #print(result[0])
    #detector.FindLanguage(text=str(df['prcsd_title'][i]))
    df['language'][i]=result[0]
    if i%10000==0:
        now = datetime.now()
        current_time = now.strftime("%H:%M:%S")
        print("Current Time =",current_time)
        print(i)

如果使用Windows操作系统,则必须安装Ubuntu。引用此视频链接https://www.youtube.com/watch?v=tQvghqdefTM&t=177s