简体   繁体   English

改进西班牙语和加泰罗尼亚语之间语言检测的想法

[英]Ideas to improve language detection between Spanish and Catalan

I'm working on a text mining script in python. I need to detect the language of a natural language field from the dataset.我正在 python 中处理文本挖掘脚本。我需要从数据集中检测自然语言字段的语言。

The thing is, 98% of the rows are in Spanish and Catalan.问题是,98% 的行都是西班牙语和加泰罗尼亚语。 I tried using some algorithms like the stopwords one or the langdetect library, but these languages share a lot of words so they fail a lot.我尝试使用一些算法,如停用langdetect stopwords ,但这些语言共享很多词,所以它们经常失败。

I'm looking for some ideas to improve this algorithm.我正在寻找一些想法来改进这个算法。

One thought is, make a dictionary with some words that are specific to Spanish and Catalan, so if one text has any of these words, it's tagged as that language.一个想法是,用一些特定于西班牙语和加泰罗尼亚语的词制作一本字典,所以如果一个文本有这些词中的任何一个,它就会被标记为该语言。

Approach 1: Distinguishing characters方法一:区分字符

Spanish and Catalan (note: there will be exceptions for proper names and loanwords eg Barça ): 西班牙语加泰罗尼亚语(注意:专有名称和借词会有例外,例如Barça ):

esp_chars = "ñÑáÁýÝ"
cat_chars = "çÇàÀèÈòÒ·ŀĿ"

Example:示例:

sample_texts = ["El año que es abundante de poesía, suele serlo de hambre.",
                "Cal no abandonar mai ni la tasca ni l'esperança."]

for text in sample_texts:
    if any(char in text for char in esp_chars):
        print("Spanish: {}".format(text))
    elif any(char in text for char in cat_chars):
        print("Catalan: {}".format(text))
>>> Spanish: El año que es abundante de poesía, suele serlo de hambre.
    Catalan: Cal no abandonar mai ni la tasca ni l'esperança.

If this isn't sufficient, you could expand this logic to search for language exclusive digraphs, letter combinations, or words:如果这还不够,您可以扩展此逻辑以搜索语言专有有向图、字母组合或单词:

Spanish only仅限西班牙语 Catalan only仅加泰罗尼亚语
Words单词 como y su con él otro como y su con él otro com i seva amb ell altre com i seva amb ell altre
Initial digraphs初始有向图 d' l' d' l'
Digraphs有向图 ss tj l·l ll ss tj l·l ll
Terminal digraphs终端有向图 ig

Catalan letter combinations that only marginally appear in Spanish加泰罗尼亚语字母组合仅在西班牙语中很少出现

  • tx
  • tg (Es. exceptions postgrado, postgraduado, postguerra ) tg (Es. 例外postgrado, postgraduado, postguerra )
  • ny (Es. exceptions mostly prefixed in-, en-, con- + y- ) ny (Es. 例外大多以in-, en-, con- + y-为前缀)
  • ll (terminal) (Es. exceptions (loanwords): detall, nomparell ) ll (终端) (Es. exceptions (loanwords): detall, nomparell )

Approach 2: googletrans library方法二: googletrans

You could also use the googletrans library to detect the language:您还可以使用googletrans库来检测语言:

from googletrans import Translator

translator = Translator()

for text in sample_texts:
    lang = translator.detect(text).lang
    print(lang, ":", text)
>>> es : El año que es abundante de poesía, suele serlo de hambre.
    ca : Cal no abandonar mai ni la tasca ni l'esperança.
DicCat = ['amb','cap','dalt','damunt','des','dintre','durant','excepte','fins','per','pro','sense','sota','llei','hi','ha','més','mes','moment','órgans', 'segóns','Article','i','per','els','amb','és','com','dels','més','seu','seva','fou','també','però','als','després','aquest','fins','any','són','hi','pel','aquesta','durant','on','part','altres','anys','ciutat','cap','des','seus','tot','estat','qual','segle','quan','ja','havia','molt','rei','nom','fer','així','li','sant','encara','pels','seves','té','partit','està','mateix','pot','nord','temps','fill','només','dues','sota','lloc','això','alguns','govern','uns','aquests','mort','nou','tots','fet','sense','frança','grup','tant','terme','fa','tenir','segons','món','regne','exèrcit','segona','abans','mentre','quals','aquestes','família','catalunya','eren','poden','diferents','nova','molts','església','major','club','estats','seua','diversos','grans','què','arribar','troba','població','poble','foren','època','haver','eleccions','diverses','tipus','riu','dia','quatre','poc','regió','exemple','batalla','altre','espanya','joan','actualment','tenen','dins','llavors','centre','algunes','important','altra','terra','antic','tenia','obres','estava','pare','qui','ara','havien','començar','història','morir','majoria','qui','ara','havien','començar','història','morir','majoria']
DicEsp = ['los','y','bajo','con', 'entre','hacia','hasta','para','por','según','segun','sin','tras','más','mas','ley','capítulo','capitulo','título','titulo','momento','y','las','por','con','su','para','lo','como','más','pero','sus','le','me','sin','este','ya','cuando','todo','esta','son','también','fue','había','muy','años','hasta','desde','está','mi','porque','qué','sólo','yo','hay','vez','puede','todos','así','nos','ni','parte','tiene','él','uno','donde','bien','tiempo','mismo','ese','ahora','otro','después','te','otros','aunque','esa','eso','hace','otra','gobierno','tan','durante','siempre','día','tanto','ella','sí','dijo','sido','según','menos','año','antes','estado','sino','caso','nada','hacer','estaba','poco','estos','presidente','mayor','ante','unos','algo','hacia','casa','ellos','ayer','hecho','mucho','mientras','además','quien','momento','millones','esto','españa','hombre','están','pues','hoy','lugar','madrid','trabajo','otras','mejor','nuevo','decir','algunos','entonces','todas','días','debe','política','cómo','casi','toda','tal','luego','pasado','medio','estas','sea','tenía','nunca','aquí','ver','veces','embargo','partido','personas','grupo','cuenta','pueden','tienen','misma','nueva','cual','fueron','mujer','frente','josé','tras','cosas','fin','ciudad','he','social','tener','será','historia','muchos','juan','tipo','cuatro','dentro','nuestro','punto','dice','ello','cualquier','noche','aún','agua','parece','haber','situación','fuera','bajo','grandes','nuestra','ejemplo','acuerdo','habían','usted','estados','hizo','nadie','países','horas','posible','tarde','ley','importante','desarrollo','proceso','realidad','sentido','lado','mí','tu','cambio','allí','mano','eran','estar','san','número','sociedad','unas','centro','padre','gente','relación','cuerpo','incluso','través','último','madre','mis','modo','problema','cinco','carlos','hombres','información','ojos','muerte','nombre','algunas','público','mujeres','siglo','todavía','meses','mañana','esos','nosotros','hora','muchas','pueblo','alguna','dar','don','da','tú','derecho','verdad','maría','unidos','podría','sería','junto','cabeza','aquel','luis','cuanto','tierra','equipo','segundo','director','dicho','cierto','casos','manos','nivel','podía','familia','largo','falta','llegar','propio','ministro','cosa','primero','seguridad','hemos','mal','trata','algún','tuvo','respecto','semana','varios','real','sé','voz','paso','señor','mil','quienes','proyecto','mercado','mayoría','luz','claro','iba','éste','pesetas','orden','español','buena','quiere','aquella','programa','palabras','internacional','esas','segunda','empresa','puesto','ahí','propia','libro','igual','político','persona','últimos','ellas','total','creo','tengo','dios','española','condiciones','méxico','fuerza','solo','único','acción','amor','policía','puerta','pesar','sabe','calle','interior','tampoco','ningún','vista','campo','buen','hubiera','saber','obras','razón','niños','presencia','tema','dinero','comisión','antonio','servicio','hijo','última','ciento','estoy','hablar','dio','minutos','producción','camino','seis','quién','fondo','dirección','papel','demás','idea','especial','diferentes','dado','base','capital','ambos','europa','libertad','relaciones','espacio','medios','ir','actual','población','empresas','estudio','salud','servicios','haya','principio','siendo','cultura','anterior','alto','media','mediante','primeros','arte','paz','sector','imagen','medida','deben','datos','consejo','personal','interés','julio','grupos','miembros','ninguna','existe','cara','edad','movimiento','visto','llegó','puntos','actividad','bueno','uso','niño','difícil','joven','futuro','aquellos','mes','pronto','soy','hacía','nuevos','nuestros','estaban','posibilidad','sigue','cerca','resultados','educación','atención','gonzález','capacidad','efecto','necesario','valor','aire','investigación','siguiente','figura','central','comunidad','necesidad','serie','organizació','nuevas','calidad']
DicEng = ['all','my','have','do','and', 'or', 'what', 'can', 'you', 'the', 'on', 'it', 'at', 'since', 'for', 'ago', 'before', 'past', 'by', 'next', 'from','with', 'wich','law','is','the','of','and','to','in','is','you','that','it','he','was','for','on','are','as','with','his','they','at','be','this','have','from','or','one','had','by','word','but','not','what','all','were','we','when','your','can','said','there','use','an','each','which','she','do','how','their','if','will','up','other','about','out','many','then','them','these','so','some','her','would','make','like','him','into','time','has','look','two','more','write','go','see','number','no','way','could','people','my','than','first','water','been','call','who','oil','its','now','find','long','down','day','did','get','come','made','may','part','may','part']


def WhichLanguage(text):
    Input = text.lower().split(" ")
    CatScore = []
    EspScore = []
    EngScore = []

    for e in Input:
        if e in DicCat:
            CatScore.append(e)
        if e in DicEsp:
            EspScore.append(e)
        if e in DicEng:
            EngScore.append(e)

    if(len(EngScore) > len(EspScore)) and (len(EngScore) > len(CatScore)):
        Language ='English'
    else:
        if(len(CatScore) > len(EspScore)):
            Language ='Catala'
        else:
            Language ='Espanyol'
    print(text)
    print("ESP= ",len(EspScore),EspScore)    
    print("Cat = ",len(CatScore), CatScore)
    print("ING= ",len(EngScore),EngScore)
    print( 'Language is =', Language)
    print("-----")
    return(Language)


print(WhichLanguage("Hola bon dia"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM