Versión 5.12.5
El analizador gramática Link exhibe la estructura lingüística (lenguaje natural) del inglés, tailandés, ruso, árabe, persa y subconjuntos limitados de media docena de otros idiomas. Esta estructura es un gráfico de enlaces tipeados (bordes) entre las palabras en una oración. Uno puede obtener el HPSG (constituyente) más convencional y los analizados de estilo de dependencia de la gramática de enlace aplicando una colección de reglas para convertir a estos diferentes formatos. Esto es posible porque la gramática de enlace se vuelve un poco "más profunda" a la estructura "sintáctica-semántica" de una oración: proporciona información considerablemente más fina y detallada de lo que comúnmente está disponible en los analizadores convencionales.
La teoría del análisis de gramática de Link fue desarrollada originalmente en 1991 por Davy Temperley, John Lafferty y Daniel Sleator, en ese momento profesores de lingüística e informática en la Universidad Carnegie Mellon. Las tres publicaciones iniciales sobre esta teoría proporcionan la mejor introducción y descripción general; Desde entonces, ha habido cientos de publicaciones explorando, examinando y extendiendo las ideas.
Aunque se basa en la base original de código Carnegie-Mellon, el paquete gramatical de enlace actual ha evolucionado drásticamente y es profundamente diferente de las versiones anteriores. Ha habido innumerables correcciones de errores; El rendimiento ha mejorado en varios órdenes de magnitud. El paquete está totalmente habilitado para múltiples subprocesos, totalmente UTF-8, y se ha fregado para la seguridad, habilitando la implementación de la nube. La cobertura de inglés del inglés se ha mejorado dramáticamente; Se han agregado otros idiomas (más notablemente, tailandés y ruso). Hay una serie de nuevas características, que incluyen soporte para la morfología, dialectos y un sistema de peso (costo) de grano fino, que permite un comportamiento de tipo vectorial. Hay un nuevo tokenizador sofisticado adaptado para la morfología: puede ofrecer divisiones alternativas para palabras morfológicamente ambiguas. Los diccionarios se pueden actualizar en tiempo de ejecución, lo que permite que los sistemas que realicen un aprendizaje continuo de gramática también analicen al mismo tiempo. Es decir, las actualizaciones de diccionario y el análisis son mutuamente seguras de hilo. Las clases de palabras se pueden reconocer con regexas. El análisis del gráfico plano aleatorio es totalmente compatible; Esto permite un muestreo uniforme del espacio de los gráficos planos. Se puede encontrar un informe detallado de lo que ha cambiado en el ChangeLog.
Este código se publica bajo la licencia LGPL, lo que la hace gratuitamente para uso privado y comercial, con pocas restricciones. Los términos de la licencia se dan en el archivo de licencia incluido con este software.
Consulte la página web principal para obtener más información. Esta versión es una continuación del analizador CMU original.
A partir de la versión 5.9.0, el sistema incluye un sistema experimental para generar oraciones. Estos se especifican utilizando una API de "llenar los espacios en blanco", donde las palabras se sustituyen en ubicaciones de tarjetas salvajes, siempre que el resultado sea una oración gramaticalmente válida. Los detalles adicionales están en la página del hombre: man link-generator (en el subdirectorio man ).
Este generador se utiliza en el proyecto OpenCog Language Learning, que tiene como objetivo aprender automáticamente las gramáticas vinculadas de los corpus, utilizando técnicas teóricas de información nuevas e innovadoras, algo similares a las que se encuentran en las redes neuronales artificiales (aprendizaje profundo), pero utilizando representaciones explícitamente simbólicas.
El analizador incluye API en varios lenguajes de programación diferentes, así como una práctica herramienta de línea de comandos para jugar con ella. Aquí hay un resultado típico:
linkparser> This is a test!
Linkage 1, cost vector = (UNUSED=0 DIS= 0.00 LEN=6)
+-------------Xp------------+
+----->WV----->+---Ost--+ |
+---Wd---+-Ss*b+ +Ds**c+ |
| | | | | |
LEFT-WALL this.p is.v a test.n !
(S (NP this.p) (VP is.v (NP a test.n)) !)
LEFT-WALL 0.000 Wd+ hWV+ Xp+
this.p 0.000 Wd- Ss*b+
is.v 0.000 Ss- dWV- O*t+
a 0.000 Ds**c+
test.n 0.000 Ds**c- Os-
! 0.000 Xp- RW+
RIGHT-WALL 0.000 RW-
Esta pantalla bastante ocupada ilustra muchas cosas interesantes. Por ejemplo, el enlace Ss*b conecta el verbo y el sujeto, e indica que el sujeto es singular. Del mismo modo, el enlace Ost conecta el verbo y el objeto, y también indica que el objeto es singular. El enlace WV (pared verbal) apunta en la cabeza-verbo de la oración, mientras que el enlace Wd apunta en el sustantivo. El enlace Xp se conecta a la puntuación final. El enlace Ds**c conecta el sustantivo al determinante: nuevamente confirma que el sustantivo es singular, y también que el sustantivo comienza con una consonante. (El enlace PH , no requerido aquí, se usa para forzar un acuerdo fonético, distinguiendo 'a' de 'an'). Estos tipos de enlaces se documentan en la documentación de enlace en inglés.
La parte inferior de la pantalla es un listado de los "disyuntivos" utilizados para cada palabra. Los disyuntamientos son simplemente una lista de los conectores que se emplearon para formar los enlaces. Son particularmente interesantes porque sirven como una forma de grano extremadamente fino de una "parte del discurso". Así, por ejemplo: el disyuntado S- O+ indica un verbo transitivo: es un verbo que toma tanto un sujeto como un objeto. El marcado adicional anterior indica que 'IS' no solo se usa como verbo transitivo, sino que también indica detalles más finos: un verbo transitivo que tomó un sujeto singular y se usó (se puede usar como) el verbo de cabeza de una oración. El valor de punto flotante es el "costo" del disyuntamiento; Captura muy o menos la idea de la probabilidad de registro de este uso gramatical particular. Al igual que las partes de voz se correlacionan con los medios de palabras, también se correlacionan las partes de la discurso de granos con distinciones mucho más finas y gradaciones de significado.
El analizador Link-Grammar también respalda el análisis morfológico. Aquí hay un ejemplo en ruso:
linkparser> это теста
Linkage 1, cost vector = (UNUSED=0 DIS= 0.00 LEN=4)
+-----MVAip-----+
+---Wd---+ +-LLCAG-+
| | | |
LEFT-WALL это.msi тест.= =а.ndnpi
El enlace LL conecta el vástago 'тест' al sufijo 'а'. El enlace MVA se conecta solo al sufijo, porque, en ruso, son los sufijos los que llevan toda la estructura sintáctica, y no los tallos. El Lexis ruso está documentado aquí.
El diccionario tailandés ahora está completamente desarrollado, cubriendo efectivamente todo el idioma. Un ejemplo en tailandés:
linkparser> นายกรัฐมนตรี ขึ้น กล่าว สุนทรพจน์
Linkage 1, cost vector = (UNUSED=0 DIS= 2.00 LEN=2)
+---------LWs--------+
| +<---S<--+--VS-+-->O-->+
| | | | |
LEFT-WALL นายกรัฐมนตรี.n ขึ้น.v กล่าว.v สุนทรพจน์.n
El enlace VS conecta dos verbos 'ขึ้น' y 'กล่าว' en una construcción verbal en serie. Aquí se documenta un resumen de los tipos de enlaces. La documentación completa de la gramática de enlace tailandés se puede encontrar aquí.
La gramática de enlace tailandés también acepta entradas etiquetadas con POS y con su nombre etiquetado. Cada palabra se puede anotar con la etiqueta POS de enlace. Por ejemplo:
linkparser> เมื่อวานนี้.n มี.ve คน.n มา.x ติดต่อ.v คุณ.pr ครับ.pt
Found 1 linkage (1 had no P.P. violations)
Unique linkage, cost vector = (UNUSED=0 DIS= 0.00 LEN=12)
+---------------------PT--------------------+
+---------LWs---------+---------->VE---------->+ |
| +<---S<---+-->O-->+ +<--AXw<-+--->O--->+ |
| | | | | | | |
LEFT-WALL เมื่อวานนี้.n[!] มี.ve[!] คน.n[!] มา.x[!] ติดต่อ.v[!] คุณ.pr[!] ครับ.pt[!]
La documentación completa para el diccionario tailandés se puede encontrar aquí.
El Diccionario Thai acepta LST20 Tagsets para POS y entidades nombradas, para cerrar la brecha entre las herramientas de PNL fundamentales y el analizador de enlace. Por ejemplo:
linkparser> linkparser> วันที่_25_ธันวาคม@DTM ของ@PS ทุก@AJ ปี@NN เป็น@VV วัน@NN คริสต์มาส@NN
Found 348 linkages (348 had no P.P. violations)
Linkage 1, cost vector = (UNUSED=0 DIS= 1.00 LEN=10)
+--------------------------------LWs--------------------------------+
| +<------------------------S<------------------------+
| | +---------->PO--------->+ |
| +----->AJpr----->+ +<---AJj<--+ +---->O---->+------NZ-----+
| | | | | | | |
LEFT-WALL วันที่_25_ธันวาคม@DTM[!] ของ@PS[!].pnn ทุก@AJ[!].jl ปี@NN[!].n เป็น@VV[!].v วัน@NN[!].na คริสต์มาส@NN[!].n
Tenga en cuenta que cada palabra anterior se anota con etiquetas POS LST20 y etiquetas NE. La documentación completa para las etiquetas POS de enlace y los etiquetas LST20 se pueden encontrar aquí. Aquí puede encontrar más información sobre LST20, por ejemplo, la guía de anotación y las estadísticas de datos, aquí.
El idioma any idioma admite gráficos planos aleatorios uniformemente muestreados:
linkparser> asdf qwer tyuiop fghj bbb
Found 1162 linkages (1162 had no P.P. violations)
+-------ANY------+-------ANY------+
+---ANY--+--ANY--+ +---ANY--+--ANY--+
| | | | | |
LEFT-WALL asdf[!] qwer[!] tyuiop[!] fghj[!] bbb[!]
El lenguaje ady también realiza divisiones morfológicas aleatorias:
linkparser> asdf qwerty fghjbbb
Found 1512 linkages (1512 had no P.P. violations)
+------------------ANY-----------------+
+-----ANY----+-------ANY------+ +---------LL--------+
| | | | |
LEFT-WALL asdf[!ANY-WORD] qwerty[!ANY-WORD] fgh[!SIMPLE-STEM].= =jbbb[!SIMPLE-SUFF]
Se puede encontrar una descripción general extendida y un resumen en la página de Wikipedia de gramática Link, que toca la mayoría de los aspectos principales de importación de la teoría. Sin embargo, no es sustituto de los artículos originales publicados sobre el tema:
Hay muchos más documentos y referencias enumeradas en el sitio web de gramática de enlace principal
Consulte también la documentación de la API C/C ++. Los enlaces para otros lenguajes de programación, incluidos Python3, Java y Node.js, se pueden encontrar en el directorio de enlaces. (Hay dos conjuntos de enlaces de JavaScript: un conjunto para la API de la biblioteca y otro conjunto para el analizador de línea de comandos).
| Contenido | Descripción |
|---|---|
| LICENCIA | La licencia que describe los términos de uso |
| Colegio de cambios | Un compendio de cambios recientes. |
| configurar | El script de configuración de GNU |
| autógeno.sh | Herramienta de mantenimiento de configuración del desarrollador |
| Link-Grammar/*. C | El programa. (Escrito en ANSI-C) |
| ---- | ---- |
| Bindings/Autoit/ | ANIFICACIONES DE LENGUA AUTOIT OPCIONALES. |
| Bindings/Java/ | ANIFICACIONES DE LENGUA DE JAVA OPCIONALES. |
| enlaces/js/ | Bintas de lenguaje opcionales de JavaScript. |
| Bindings/Lisp/ | Vínculos de lenguaje LISP comunes opcionales. |
| enlaces/node.js/ | Bintings de lenguaje Node.js opcionales. |
| Bindings/Ocaml/ | Viniamientos de lenguaje OCAML opcionales. |
| Bindings/Python/ | ANILLAS DE LENGUA DE PYTHON3 OPCIONALES. |
| Bindings/Python-Examples/ | Ejemplo de uso de la suite de prueba de gramática de enlaces y el lenguaje de la pitón. |
| Bindings/Swig/ | Archivo de interfaz SWIG, para otras interfaces FFI. |
| Bindings/Vala/ | Vinculaciones opcionales del lenguaje Vala. |
| ---- | ---- |
| datos/EN/ | Dicción en inglés. |
| Datos/EN/4.0.dicto | El archivo que contiene las definiciones del diccionario. |
| Datos/EN/4.0. Conocimiento | El archivo de conocimiento posterior al procesamiento. |
| datos/EN/4.0.constituyentes | El archivo de conocimiento constituyente. |
| Datos/EN/4.0.Affix | El archivo Affix (prefijo/sufijo). |
| Datos/EN/4.0.regex | Adivinador de morfología basado en la expresión regular. |
| datos/en/tiny.dict | Un pequeño diccionario de ejemplo. |
| datos/en/palabras/ | Un directorio lleno de listas de palabras. |
| datos/en/corpus*.Batch | Ejemplo de corpus utilizados para las pruebas. |
| ---- | ---- |
| datos/Ru/ | Un diccionario ruso completo |
| datos/th/ | Un diccionario tailandés completo (más de 100,000 palabras) |
| datos/AR/ | Un diccionario árabe bastante completo |
| datos/fa/ | Un diccionario persa (farsi) |
| datos/DE/ | Un pequeño prototipo de diccionario alemán |
| datos/LT/ | Un pequeño prototipo de diccionario lituano |
| Datos/ID/ | Un pequeño prototipo de diccionario indonesio |
| datos/VN/ | Un pequeño prototipo de diccionario vietnamita |
| datos/él/ | Un diccionario hebreo experimental |
| datos/kz/ | Un diccionario experimental de kazajos |
| datos/tr/ | Un diccionario turco experimental |
| ---- | ---- |
| morfología/ar/ | Un analizador de morfología árabe |
| morfología/fa/ | Un analizador de morfología persa |
| ---- | ---- |
| depurar/ | Información sobre la depuración de la biblioteca |
| MSVC/ | Archivos del proyecto Microsoft Visual-C |
| Mingw/ | Información sobre el uso de MingW en MSYS o CyGwin |
El sistema se distribuye utilizando el formato tar.gz convencional; Se puede extraer utilizando el comando tar -zxf link-grammar.tar.gz en la línea de comando.
Se puede descargar un tarball de la última versión:
https://www.gnucash.org/link-grammar/downloads/
Los archivos se han firmado digitalmente para asegurarse de que no hubiera corrupción del conjunto de datos durante la descarga, y para ayudar a garantizar que no se hicieran cambios maliciosos en el código internal por terceros. Las firmas se pueden verificar con el comando GPG:
gpg --verify link-grammar-5.12.5.tar.gz.asc
que debería generar la salida idéntica a (excepto para la fecha):
gpg: Signature made Thu 26 Apr 2012 12:45:31 PM CDT using RSA key ID E0C0651C
gpg: Good signature from "Linas Vepstas (Hexagon Architecture Patches) <[email protected]>"
gpg: aka "Linas Vepstas (LKML) <[email protected]>"
Alternativamente, se pueden verificar las suma de verificación MD5. Estos no proporcionan seguridad criptográfica, pero pueden detectar una corrupción simple. Para verificar el suma de verificación, emita md5sum -c MD5SUM en la línea de comando.
Las etiquetas en git se pueden verificar realizando lo siguiente:
gpg --recv-keys --keyserver keyserver.ubuntu.com EB6AA534E0C0651C
git tag -v link-grammar-5.10.5
Para compilar la biblioteca compartida de la gramática de enlace y el programa de demostración, en la línea de comando, escriba:
./configure
make
make check
Para instalar, cambie el usuario a "root" y diga
make install
ldconfig
Esto instalará la biblioteca liblink-grammar.so en /usr/local/lib , los archivos de encabezado en /usr/local/include/link-grammar , y los diccionarios en /usr/local/share/link-grammar . Ejecutar ldconfig reconstruirá el caché de la biblioteca compartida. Para verificar que la instalación fue exitosa, ejecute (como un usuario no raíz)
make installcheck
La biblioteca Link-Grammar tiene características opcionales que están habilitadas automáticamente si configure detecta ciertas bibliotecas. Estas bibliotecas son opcionales en la mayoría de los sistemas y si se desea la característica que agregan, las bibliotecas correspondientes deben instalarse antes de ejecutar configure .
Los nombres de los paquetes de la biblioteca pueden variar en varios sistemas (consulte a Google si es necesario ...). Por ejemplo, los nombres pueden incluir -devel en lugar de -dev , o estar sin él por completo. Los nombres de la biblioteca pueden estar sin el prefijo lib .
libsqlite3-dev (para el diccionario respaldado por SQLite)libz1g-dev o libz-devel (actualmente necesario para el minisat2 agrupado)libedit-dev (ver edit Line)libhunspell-dev o libaspell-dev (y el diccionario inglés correspondiente).libtre-dev o libpcre2-dev (mucho más rápido que la implementación de LibC Regex, y necesaria para la corrección en FreEBSD y Cygwin).libpcre2-dev se recomienda fuertemente. Debe usarse en ciertos sistemas (como se especifica en las secciones de su edificio). Si se instala libedit-dev , entonces las teclas de flecha se pueden usar para editar la entrada en la herramienta Parser de enlace; Las teclas de flecha hacia arriba y hacia abajo recuperarán las entradas anteriores. Quieres esto; Hace que las pruebas y la edición sean mucho más fáciles.
Se incluyen dos versiones de Node.js Bindings. Una versión envuelve la biblioteca; El otro usa EMScripten para envolver la herramienta de línea de comandos. Los enlaces de la biblioteca están en bindings/node.js mientras que el envoltorio EMScripten está en bindings/js .
Estos se construyen con npm . Primero, debe construir la biblioteca Core C. Luego haz lo siguiente:
cd bindings/node.js
npm install
npm run make
Esto creará los enlaces de la biblioteca y también ejecutará una pequeña prueba unitaria (que debe pasar). Se puede encontrar un ejemplo en bindings/node.js/examples/simple.js .
Para el envoltorio de línea de comandos, haga lo siguiente:
cd bindings/js
./install_emsdk.sh
./build_packages.sh
Los enlaces Python3 se construyen de forma predeterminada, siempre que se instalen los paquetes de desarrollo de Python correspondientes. (Las fijaciones de Python2 ya no son compatibles).
Estos paquetes son:
python3-develpython3-dev Nota: Antes de emitir configure (ver más abajo) debe validar que las versiones de Python requeridas se pueden invocar utilizando su PATH .
El uso de las enlaces de Python es opcional ; No los necesita si no planea usar la gramática de enlace con Python. Si desea deshabilitar las enlaces de Python, use:
./configure --disable-python-bindings
El módulo linkgrammar.py proporciona una interfaz de alto nivel en Python. Los scripts de example.py y sentence-check.py proporcionan una demostración, y tests.py ejecuta pruebas unitarias.
make install pythondir=/where/to/install De manera predeterminada, el intento Makefile S de construir las enlaces de Java. El uso de las enlaces Java es opcional ; No los necesita si no planea usar la gramática de enlace con Java. Puede omitir la construcción de los enlaces Java deshabilitando lo siguiente:
./configure --disable-java-bindings
Si no se encuentra jni.h , o si no se encuentra ant , entonces las enlaces de Java no se construirán.
Notas sobre la búsqueda de jni.h :
Algunas distribuciones comunes de Java JVM (sobre todo, las de Sun) colocan este archivo en ubicaciones inusuales, donde no se puede encontrar automáticamente. Para remediar esto, asegúrese de que la variable de entorno JAVA_HOME esté configurada correctamente. El script de configuración busca jni.h en $JAVA_HOME/Headers y en $JAVA_HOME/include ; También examina las ubicaciones correspondientes para $JDK_HOME . Si no se puede encontrar jni.h , especifique la ubicación con la variable CPPFLAGS : Entonces, por ejemplo,
export CPPFLAGS="-I/opt/jdk1.5/include/:/opt/jdk1.5/include/linux"
o
export CPPFLAGS="-I/c/java/jdk1.6.0/include/ -I/c/java/jdk1.6.0/include/win32/"
Tenga en cuenta que el uso de /opt no es estándar, y la mayoría de las herramientas del sistema no encontrarán paquetes instalados allí.
El objetivo de instalación /usr/local puede estar en exceso utilizando la opción GNU configure --prefix ; Entonces, por ejemplo:
./configure --prefix=/opt/link-grammar
Al usar pkg-config (ver más abajo), las ubicaciones de instalación no estándar se pueden detectar automáticamente.
Las opciones de configuración adicionales se imprimen por
./configure --help
El sistema ha sido probado y funciona bien en sistemas Linux de 32 y 64 bits, FreeBSD, MacOS, así como en los sistemas de Microsoft Windows. Sigue las notas específicas dependientes del sistema operativo.
Los usuarios finales deben descargar el tarball (ver Desempaquetado y verificación de firma).
La versión actual de GitHub está destinada a los desarrolladores (incluidos cualquier persona que esté dispuesta a proporcionar una solución, una nueva característica o una mejora). La punta de la rama maestra a menudo es inestable y, a veces, puede tener un código malo como está en desarrollo. También necesita la instalación de herramientas de desarrollo que no están instaladas de forma predeterminada. Debido a esta razón, el uso de la versión GitHub se desaconseja para los usuarios finales regulares.
Clon It: git clone https://github.com/opencog/link-grammar.git
O descargarlo como un zip:
https://github.com/opencog/link-grammar/archive/master.zip
Herramientas que pueden necesitar instalación antes de que pueda construir la gramática de enlace:
make (la variante gmake puede ser necesaria)
m4
gcc o clang
autoconf
libtool
autoconf-archive
pkg-config (puede llamarse pkgconf o pkgconfig )
pip3 (para las fijaciones de Python)
Opcional:
swig (para enlaces de idiomas)
flex
APACHE ANT (para enlaces de Java)
graphviz (si desea usar la función de visualización de Word-Graph)
La versión de GitHub no incluye un script configure . Para generarlo, use:
autogen.sh
Si obtiene errores, asegúrese de haber instalado los paquetes de desarrollo mencionados anteriormente y que la instalación de su sistema esté actualizado. Especialmente, faltar autoconf o autoconf-archive puede causar errores extraños y engañosos.
Para obtener más información sobre cómo proceder, continúe en la sección creando el sistema y las secciones relevantes después de él.
Para configurar el modo de depuración , use:
configure --enable-debug
Agrega algunos código de depuración de verificación y funciones que pueden imprimir bastante estructuras de datos.
Una característica que puede ser útil para la depuración es la pantalla Word-Graph. Está habilitado de forma predeterminada. Para obtener más detalles sobre esta función, consulte la pantalla de Graph de palabras.
La configuración actual tiene un problema de mezcla de biblioteca C ++ estándar aparente cuando se usa gcc (una solución es bienvenida). Sin embargo, la práctica común en FreeBSD es compilar con clang , y no tiene este problema. Además, los paquetes de complementos se instalan en /usr/local .
Así que así es como se debe invocar configure :
env LDFLAGS=-L/usr/local/lib CPPFLAGS=-I/usr/local/include
CC=clang CXX=clang++ configure
Tenga en cuenta que pcre2 es un paquete requerido, ya que la implementación existente libc Regex no tiene el nivel necesario de soporte Regex.
Algunos paquetes tienen nombres diferentes a los mencionados en las secciones anteriores:
minisat (Minisat2) pkgconf (PKG-Config)
La gramática de enlace de anirina simple debe compilarse y ejecutar en Apple macOS bien, como se describió anteriormente. En este momento, no hay problemas reportados.
Si no necesita los enlaces Java, casi seguramente debe configurar con:
./configure --disable-java-bindings
Si desea ataduras de Java, asegúrese de establecer la variable de entorno JDK_HOME en donde sea <Headers/jni.h> . Establezca la variable Java_Home en la ubicación del compilador Java. Asegúrese de tener hormiga instalada.
Si desea construir desde GitHub (consulte el edificio desde el repositorio de GitHub), puede instalar las herramientas que se enumeran allí usando HomeBrew.
Hay tres formas diferentes en que la gramática del enlace se puede compilar en Windows. Una forma es usar Cygwin, que proporciona una capa de compatibilidad de Linux para Windows. Otra forma es usar el sistema MSVC. Una tercera forma es usar el sistema MINGW, que utiliza el conjunto de herramientas GNU para compilar programas de Windows. El código fuente admite los sistemas Windows de Vista On.
La forma cygwin actualmente produce el mejor resultado, ya que admite la edición de línea con la finalización del comando y el historial y también admite la visualización de grifos de palabras en X-Windows. (Mingw actualmente no tiene libedit , y el puerto MSVC actualmente no admite la finalización e historia del comando, y también la ortografía.
La forma más fácil de hacer que Link-Grammar funcione en MS Windows es usar Cygwin, un entorno similar a Linux para Windows que hace posible portuar el software que se ejecuta en sistemas POSIX a Windows. Descargue e instale cygwin.
Tenga en cuenta que se requiere la instalación del paquete pcre2 porque la implementación de Libc Regex no es lo suficientemente capaz.
Para más detalles, consulte Mingw/ReadMe-Cygwin.md.
Otra forma de construir la gramática de enlaces es usar MingW, que utiliza el conjunto de herramientas GNU para compilar programas que cumplen con POSIX para Windows. El uso de Mingw/MSYS2 es probablemente la forma más fácil de obtener enlaces Java viables para Windows. Descargue e instale mingw/msys2 de msys2.org.
Tenga en cuenta que se requiere la instalación del paquete pcre2 porque la implementación de Libc Regex no es lo suficientemente capaz.
Para más detalles, consulte Mingw/ReadMe-Mingw64.md.
Los archivos del proyecto Microsoft Visual C/C ++ se pueden encontrar en el directorio msvc . Para obtener instrucciones, consulte el archivo ReadMe.md allí.
Para ejecutar el programa del programa el comando (suponiendo que está en su camino):
link-parser [arguments]
Esto inicia el programa. El programa tiene muchas variables y opciones establecibles con el usuario. Estos se pueden mostrar entrando !var Entrando !help mostrará algunos comandos adicionales.
Los diccionarios están organizados en directorios cuyo nombre es el código de idioma de 2 letras. El programa Parser de enlace busca dicho directorio de idiomas en ese orden, directamente o bajo data de nombres de un directorio:
/usr/local/share/link-grammar ).Si Link-Parser no puede encontrar el diccionario deseado, use el nivel de verbosidad 4 para depurar el problema; Por ejemplo:
link-parser ru -verbosity=4
Se pueden especificar otras ubicaciones en la línea de comando; Por ejemplo:
link-parser ../path/to-my/modified/data/en
Al acceder a los diccionarios en ubicaciones no estándar, los nombres de archivo estándar todavía se asumen ( es decir , 4.0.dict , 4.0.affix , etc. ).
Los diccionarios rusos están en data/ru . Por lo tanto, el analizador ruso puede iniciarse como:
link-parser ru
Si no suministra un argumento a Link-Parser, busca un idioma de acuerdo con la configuración de su localidad actual. Si no puede encontrar dicho directorio de idiomas, es predeterminado a "EN".
Si ve errores similares a este:
Warning: The word "encyclop" found near line 252 of en/4.0.dict
matches the following words:
encyclop
This word will be ignored.
entonces sus locales UTF-8 no están instalados o no están configurados. La locale -a debe enumerar en_US.utf8 como un local. Si no es así, debe ser dpkg-reconfigure locales y/o ejecutar update-locale o posiblemente apt-get install locales , o combinaciones o variantes de estos, dependiendo de su sistema operativo.
Hay varias formas de probar la construcción resultante. Si se construyen los enlaces de Python, se puede encontrar un programa de prueba en el archivo ./bindings/python-examples/tests.py : cuando se ejecuta, debe pasar. Para obtener más detalles, consulte ReadMe.md en el directorio bindings/python-examples .
También hay múltiples lotes de oraciones de prueba/ejemplo en los directorios de datos del lenguaje, que generalmente tienen el corpus-*.batch El programa PARSER se puede ejecutar en modo por lotes, para probar el sistema en una gran cantidad de oraciones. El siguiente comando ejecuta el analizador en un archivo llamado corpus-basic.batch ;
link-parser < corpus-basic.batch
La línea !batch cerca de la parte superior de Corpus-Basic.Batch enciende el modo por lotes. En este modo, las oraciones etiquetadas con una inicial * deben ser rechazadas y las que no comienzan con A * deben aceptarse. Este archivo por lotes informa algunos errores, al igual que los archivos corpus-biolg.batch y corpus-fixes.batch . El trabajo está en curso para solucionarlos.
El archivo corpus-fixes.batch contiene muchos miles de oraciones que se han solucionado desde la versión original 4.1 de la gramática de enlace. El corpus-biolg.batch contiene oraciones de biología/texto médico del proyecto Biolg. El corpus-voa.batch contiene muestras de Voice of America; El corpus-failures.batch contiene una gran cantidad de fallas.
Los siguientes números están sujetos a cambios, pero, en este momento, el número de errores que uno puede esperar observar en cada uno de estos archivos son más o menos como el siguiente:
en/corpus-basic.batch: 88 errors
en/corpus-fixes.batch: 371 errors
lt/corpus-basic.batch: 15 errors
ru/corpus-basic.batch: 47 errors
El directorio de enlaces/pitón contiene una prueba unitaria para las uniones de Python. También realiza varias comprobaciones básicas que enfatizan las bibliotecas de gramática del enlace.
Hay una API (interfaz del programa de aplicación) al analizador. Esto hace que sea fácil incorporarlo a sus propias aplicaciones. La API está documentada en el sitio web.
El archivo FindLinkGrammar.cmake se puede usar para probar y configurar la compilación en entornos de compilación basados en CMake.
Para facilitar la compilación y el enlace, la versión actual utiliza el sistema PKG-Config. Para determinar la ubicación de los archivos de encabezado de gramática del enlace, digamos pkg-config --cflags link-grammar para obtener la ubicación de las bibliotecas, digamos pkg-config --libs link-grammar , por ejemplo, un makile típico puede incluir los objetivos:
.c.o:
cc -O2 -g -Wall -c $< `pkg-config --cflags link-grammar`
$(EXE): $(OBJS)
cc -g -o $@ $^ `pkg-config --libs link-grammar`
Esta versión proporciona archivos Java que ofrecen tres formas de acceder al analizador. La forma más simple es usar la clase org.linkgrammar.linkgrammar; Esto proporciona una API Java muy simple al analizador.
La segunda posibilidad es usar la clase LGService. Esto implementa un servidor de red TCP/IP, proporcionando resultados de análisis como mensajes JSON. Cualquier cliente con capacidad JSON puede conectarse a este servidor y obtener texto analizado.
La tercera posibilidad es usar la clase org.linkgrammar.lgremoteclient, y en particular, el método parse (). Esta clase es un cliente de red que se conecta al servidor JSON y convierte la respuesta a los resultados accesibles a través de la API Parseresult.
El código descrito anteriormente se construirá si se instala Apache ant .
El servidor de red se puede iniciar diciendo:
java -classpath linkgrammar.jar org.linkgrammar.LGService 9000
El anterior inicia el servidor en el puerto 9000. Se omite el puerto, se imprime el texto de ayuda. Este servidor se puede contactar directamente a través de TCP/IP; Por ejemplo:
telnet localhost 9000
(Alternativamente, use NetCat en lugar de Telnet). Después de conectarse, escriba:
text: this is an example sentence to parse
Los bytes devueltos serán un mensaje JSON que proporcione los analizados de la oración. Por defecto, el análisis Ascii-ART del texto no se transmite. Esto se puede obtener enviando mensajes del formulario:
storeDiagramString:true, text: this is a test.
El analizador ejecutará un corrector ortográfico en una etapa temprana, si encuentra una palabra que no sabe, y no puede adivinar, basada en la morfología. El script Configurar busca los corredores ortográficos de Aspell o Hunspell; Si se encuentra el entorno ASPELL Desvel, entonces se usa Aspell, de lo contrario se usa Hunspell.
La adivinación de hechizos puede desactivarse en tiempo de ejecución, en el cliente de Link-Parser con la bandera !spell=0 . Ingrese !help para más detalles.
PRECAUCIÓN: ASPELL Versión 0.60.8 y posiblemente otros tienen una fuga de memoria. El uso de la adivinación de hechizos en los servidores de producción está muy desanimado. Mantener la adquisición de hechizos deshabilitado ( =0 ) en Parse_Options es seguro.
Es seguro usar la gramática de enlace en múltiples hilos. Los hilos pueden compartir el mismo diccionario. Las opciones de análisis se pueden establecer por subproceso, con la excepción de la verbosidad, que es un global, compartido por todos los hilos. Es el único global.
A/A Determinadores fonéticos antes de las consonantes/vocales se manejan mediante un nuevo tipo de enlace de pH, vinculando el determinante con la palabra inmediatamente después. Estado: Introducido en la versión 5.1.0 (agosto de 2014). Principalmente hecho, aunque muchos sustantivos de casos especiales están inacabados.
Se necesitan enlaces direccionales para algunos idiomas, como los idiomas lituanos, turcos y otros idiomas de orden gratuito. El objetivo es tener un enlace claramente indicar qué palabra es la palabra principal, y cuál es la dependiente. Esto se logra mediante el prefijo de conectores con una sola letra minúscula : H, D, que indica 'cabeza' y 'dependiente'. Las reglas de enlace son tales que H coincide con nada ni D, y D coincide con H o nada. Esta es una nueva característica en la versión 5.1.0 (agosto de 2014). El sitio web proporciona documentación adicional.
Aunque los enlaces de gramática del enlace en inglés no están orientados, parece que se les puede dar una dirección de facto que es completamente consistente con las concepciones estándar de una gramática de dependencia.
Las flechas de dependencia tienen las siguientes propiedades:
Antirreflexivo (una palabra no puede depender de sí misma; no puede señalar a sí misma).
Antisimétrico (si Word1 depende de Word2, entonces Word2 no puede depender de Word1) (entonces, por ejemplo, los determinantes dependen de los sustantivos, pero nunca viceversa)
Las flechas no son transitivas ni anti-transitivas: varias cabezas pueden gobernar una sola palabra. Por ejemplo:
+------>WV------->+
+-->Wd-->+<--Ss<--+
| | |
LEFT-WALL she thinks.v
Es decir, hay un camino hacia el sujeto, "Ella", directamente desde la pared izquierda, a través del enlace WD, así como indirectamente, desde la pared hasta el verbo raíz, y de allí al sujeto. Forma de bucles similares con los enlaces B y R. Dichos bucles son útiles para restringir el posible número de analizados: la restricción ocurre junto con la meta-regla "sin enlaces cruzados".
Hay varias nociones matemáticas relacionadas, pero ninguna captura LG direccional:
Los gráficos direccionales de LG se parecen a los DAG, excepto que LG permite solo una pared (un elemento "superior").
Los gráficos de LG direccionales se asemejan a órdenes parciales estrictas, excepto que las flechas de LG generalmente no son transitivas.
Los gráficos de LG direccionales se parecen a Catena, excepto que Catena es estrictamente anti-transitiva: el camino hacia cualquier palabra es único, en una Catena.
Los documentos LG fundacionales exigen la planaridad de los gráficos de análisis. Esto se basa en una observación muy antigua de que las dependencias casi nunca se cruzan en idiomas naturales: los humanos simplemente no hablan en oraciones donde los enlaces cruzan. La imposición de restricciones de planaridad proporciona una fuerte ingeniería y una restricción algorítmica en los PARSE resultantes: el número total de PARSE a considerar se reduce considerablemente y, por lo tanto, la velocidad general de análisis puede aumentar considerablemente.
Sin embargo, hay excepciones ocasionales y relativamente raras a esta regla de planaridad; Tales excepciones se observan en casi todos los idiomas. Se dan varias de estas excepciones para el inglés, a continuación.
Por lo tanto, parece importante relajar la restricción de la planaridad y encontrar algo más que sea casi tan estricto, pero aún permite excepciones poco frecuentes. Parece que el concepto de "transitividad histórica" según lo definido por Richard Hudson en su teoría de "Word Grammar", y luego defendida por Ben Goertzel, podría ser un mecanismo así.
ftp://ftp.phon.ucl.ac.uk/pub/word-grammar/ell2-wg.pdf
http://www.phon.ucl.ac.uk/home/dick/enc/syntax.htm
http://goertzel.org/powlgrammar.pdf
En la práctica, la restricción de planaridad permite utilizar algoritmos muy eficientes en la implementación del analizador. Por lo tanto, desde el punto de vista de la implementación, queremos mantener la planaridad. Afortunadamente, hay una forma conveniente e inequívoca de tener nuestro pastel y comerlo también. Se puede dibujar un diagrama no planar en una hoja de papel utilizando notación estándar de ingeniería eléctrica: un símbolo divertido, donde se cruzan los cables. Esta notación se adapta muy fácilmente a los conectores LG; A continuación se muestra un ejemplo de trabajo real, ya implementado en el diccionario LG English actual. ¡Todos los cruces de enlaces se pueden implementar de esta manera! Por lo tanto, no tenemos que abandonar los algoritmos de análisis actuales para obtener diagramas no planos. ¡Ni siquiera tenemos que modificarlos! ¡Hurra!
Aquí hay un ejemplo de funcionamiento: "Quiero mirar y escuchar todo". Esto quiere dos enlaces J que apuntan a 'todo'. El diagrama deseado tendría que verse así:
+---->WV---->+
| +--------IV---------->+
| | +<-VJlpi--+
| | | +---xxx------------Js------->+
+--Wd--+-Sp*i+--TO-+-I*t-+-MVp+ +--VJrpi>+--MVp-+---Js->+
| | | | | | | | | |
LEFT-WALL I.p want.v to.r look.v at and.j-v listen.v to.r everything
Lo anterior realmente quiere tener un enlace Js de 'At' a 'Everything', pero este enlace Js cruza (se enfrenta con - marcado por xxx) el enlace a la conjunción. Otros ejemplos sugieren que uno debería permitir que la mayoría de los enlaces cruzen los enlaces descendentes a las conjunciones.
El mantenimiento de la planaridad trabajado es dividir el enlace Js en dos: una parte Jj y una parte Jk ; Los dos se usan juntos para cruzar la conjunción. Esto se implementa actualmente en el diccionario inglés y funciona.
Esta solución al trabajo es de hecho completamente genérica y puede extenderse a cualquier tipo de cruce de enlaces. Para que esto funcione, una mejor notación sería conveniente; perhaps uJs- instead of Jj- and vJs- instead of Jk- , or something like that ... (TODO: invent better notation.) (NB: This is a kind of re-invention of "fat links", but in the dictionary, not in the code.)
Given that non-planar parses can be enabled without any changes to the parser algorithm, all that is required is to understand what sort of theory describes link-crossing in a coherent grounding. That theory is Dick Hudson's Landmark Transitivity, explained here.
This mechanism works as follows:
First, every link must be directional, with a head and a dependent. That is, we are concerned with directional-LG links, which are of the form x--A-->y or y<--A--x for words x,y and LG link type A.
Given either the directional-LG relation x--A-->y or y<--A--x, define the dependency relation x-->y. That is, ignore the link-type label.
Heads are landmarks for dependents. If the dependency relation x-->y holds, then x is said to be a landmark for y, and the predicate land(x,y) is true, while the predicate land(y,x) is false. Here, x and y are words, while --> is the landmark relation.
Although the basic directional-LG links form landmark relations, the total set of landmark relations is extended by transitive closure. That is, if land(x,y) and land(y,z) then land(x,z). That is, the basic directional-LG links are "generators" of landmarks; they generate by means of transitivity. Note that the transitive closure is unique.
In addition to the above landmark relation, there are two additional relations: the before and after landmark relations. (In English, these correspond to left and right; in Hebrew, the opposite). That is, since words come in chronological order in a sentence, the dependency relation can point either left or right. The previously-defined landmark relation only described the dependency order; we now introduce the word-sequence order. Thus, there are are land-before() and land-after() relations that capture both the dependency relation, and the word-order relation.
Notation: the before-landmark relation land-B(x,y) corresponds to x-->y (in English, reversed in right-left languages such as Hebrew), whereas the after-landmark relation land-A(x,y) corresponds to y<--x. That is, land(x,y) == land-B(x,y) or land-A(x,y) holds as a statement about the predicate form of the relations.
As before, the full set of directional landmarks are obtained by transitive closure applied to the directional-LG links. Two different rules are used to perform this closure:
-- land-B(x,y) and land(y,z) ==> land-B(x,y)
-- land-A(x,y) and land(y,z) ==> land-A(x,y)
Parsing is then performed by joining LG connectors in the usual manner, to form a directional link. The transitive closure of the directional landmarks are then computed. Finally, any parse that does not conclude with the "left wall" being the upper-most landmark is discarded.
Here is an example where landmark transitivity provides a natural solution to a (currently) broken parse. The "to.r" has a disjunct "I+ & MVi-" which allows "What is there to do?" to parse correctly. However, it also allows the incorrect parse "He is going to do". The fix would be to force "do" to take an object; however, a link from "do" to "what" is not allowed, because link-crossing would prevent it.
Fixing this requires only a fix to the dictionary, and not to the parser itself.
Examples where the no-links-cross constraint seems to be violated, in English:
"He is either in the 105th or the 106th battalion."
"He is in either the 105th or the 106th battalion."
Both seem to be acceptable in English, but the ambiguity of the "in-either" temporal ordering requires two different parse trees, if the no-links-cross rule is to be enforced. This seems un-natural. Similarmente:
"He is either here or he is there."
"He either is here or he is there."
A different example involves a crossing to the left wall. That is, the links LEFT-WALL--remains crosses over here--found :
"Here the remains can be found."
Other examples, per And Rosta:
The allowed--by link crosses cake--that :
He had been allowed to eat a cake by Sophy that she had made him specially
a--book , very--indeed
"a very much easier book indeed"
an--book , easy--to
"an easy book to read"
a--book , more--than
"a more difficult book than that one"
that--have crosses remains--of
"It was announced that remains have been found of the ark of the covenant"
There is a natural crossing, driven by conjunctions:
"I was in hell yesterday and heaven on Tuesday."
the "natural" linkage is to use MV links to connect "yesterday" and "on Tuesday" to the verb. However, if this is done, then these must cross the links from the conjunction "and" to "heaven" and "hell". This can be worked around partly as follows:
+-------->Ju--------->+
| +<------SJlp<----+
+<-SX<-+->Pp->+ +-->Mpn->+ +->SJru->+->Mp->+->Js->+
| | | | | | | | |
I was in hell yesterday and heaven on Tuesday
but the desired MV links from the verb to the time-prepositions "yesterday" and "on Tuesday" are missing -- whereas they are present, when the individual sentences "I was in hell yesterday" and "I was in heaven on Tuesday" are parsed. Using a conjunction should not wreck the relations that get used; but this requires link-crossing.
"Sophy wondered up to whose favorite number she should count"
Here, "up_to" must modify "number", and not "whose". There's no way to do this without link-crossing.
Link Grammar can be understood in the context of type theory. A simple introduction to type theory can be found in chapter 1 of the HoTT book. This book is freely available online and strongly recommended if you are interested in types.
Link types can be mapped to types that appear in categorial grammars. The nice thing about link-grammar is that the link types form a type system that is much easier to use and comprehend than that of categorial grammar, and yet can be directly converted to that system! That is, link-grammar is completely compatible with categorial grammar, and is easier-to-use. See the paper "Combinatory Categorial Grammar and Link Grammar are Equivalent" for details.
The foundational LG papers make comments to this effect; however, see also work by Bob Coecke on category theory and grammar. Coecke's diagrammatic approach is essentially identical to the diagrams given in the foundational LG papers; it becomes abundantly clear that the category theoretic approach is equivalent to Link Grammar. See, for example, this introductory sketch http://www.cs.ox.ac.uk/people/bob.coecke/NewScientist.pdf and observe how the diagrams are essentially identical to the LG jigsaw-puzzle piece diagrams of the foundational LG publications.
If you have any questions, please feel free to send a note to the mailing list.
The source code of link-parser and the link-grammar library is located at GitHub.
For bug reports, please open an issue there.
Although all messages should go to the mailing list, the current maintainers can be contacted at:
Linas Vepstas - <[email protected]>
Amir Plivatsky - <[email protected]>
Dom Lachowicz - <[email protected]>
A complete list of authors and copyright holders can be found in the AUTHORS file. The original authors of the Link Grammar parser are:
Daniel Sleator [email protected]
Computer Science Department 412-268-7563
Carnegie Mellon University www.cs.cmu.edu/~sleator
Pittsburgh, PA 15213
Davy Temperley [email protected]
Eastman School of Music 716-274-1557
26 Gibbs St. www.link.cs.cmu.edu/temperley
Rochester, NY 14604
John Lafferty [email protected]
Computer Science Department 412-268-6791
Carnegie Mellon University www.cs.cmu.edu/~lafferty
Pittsburgh, PA 15213
Some working notes.
Easy to fix: provide a more uniform API to the constituent tree. ie provide word index. Also, provide a better word API, showing word extent, subscript, etc.
There are subtle technical issues for handling capitalized first words. This needs to be fixed. In addition, for now these words are shown uncapitalized in the result linkages. This can be fixed.
Maybe capitalization could be handled in the same way that a/an could be handled! After all, it's essentially a nearest-neighbor phenomenon!
See also issue 690
The proximal issue is to add a cost, so that Bill gets a lower cost than bill.n when parsing "Bill went on a walk". The best solution would be to add a 'capitalization-mark token' during tokenization; this token precedes capitalized words. The dictionary then explicitly links to this token, with rules similar to the a/an phonetic distinction. The point here is that this moves capitalization out of ad-hoc C code and into the dictionary, where it can be handled like any other language feature. The tokenizer includes experimental code for that.
The old for parse ranking via corpus statistics needs to be revived. The issue can be illustrated with these example sentences:
"Please the customer, bring in the money"
"Please, turn off the lights"
In the first sentence, the comma acts as a conjunction of two directives (imperatives). In the second sentence, it is much too easy to mistake "please" for a verb, the comma for a conjunction, and come to the conclusion that one should please some unstated object, and then turn off the lights. (Perhaps one is pleasing by turning off the lights?)
When a sentence fails to parse, look for:
Poor agreement might be handled by giving a cost to mismatched lower-case connector letters.
An common phenomenon in English is that some words that one might expect to "properly" be present can disappear under various conditions. Below is a sampling of these. Some possible solutions are given below.
Expressions such as "Looks good" have an implicit "it" (also called a zero-it or phantom-it) in them; that is, the sentence should really parse as "(it) looks good". The dictionary could be simplified by admitting such phantom words explicitly, rather than modifying the grammar rules to allow such constructions. Other examples, with the phantom word in parenthesis, include:
This can extend to elided/unvoiced syllables:
Elided punctuation:
Normally, the subjects of imperatives must always be offset by a comma: "John, give me the hammer", but here, in muttering an oath, the comma is swallowed (unvoiced).
Some complex phantom constructions:
See also GitHub issue #224.
Actual ellipsis:
Here, the ellipsis stands for a subordinate clause, which attaches with not one, but two links: C+ & CV+ , and thus requires two words, not one. There is no way to have the ellipsis word to sink two connectors starting from the same word, and so some more complex mechanism is needed. The solution is to infer a second phantom ellipsis:
where the first ellipsis is a stand in for the subject of a subordinate clause, and the second stands in for an unknown verb.
Many (unstressed) syllables can be elided; in modern English, this occurs most commonly in the initial unstressed syllable:
Poorly punctuated sentences cause problems: for example:
"Mike was not first, nor was he last."
"Mike was not first nor was he last."
The one without the comma currently fails to parse. How can we deal with this in a simple, fast, elegant way? Similar questions for zero-copula and zero-that sentences.
Consider an argument between a professor and a dean, and the dean wants the professor to write a brilliant review. At the end of the argument, the dean exclaims: "I want the review brilliant!" This is a predicative adjective; clearly it means "I want the review [that you write to be] brilliant." However, taken out of context, such a construction is ungrammatical, as the predictiveness is not at all apparent, and it reads just as incorrectly as would "*Hey Joe, can you hand me that review brilliant?"
"Push button"
"Push button firmly"
The subject is a phantom; the subject is "you".
One possible solution is to perform a one-point compactification. The dictionary contains the phantom words, and their connectors. Ordinary disjuncts can link to these, but should do so using a special initial lower-case letter (say, 'z', in addition to 'h' and 'd' as is currently implemented). The parser, as it works, examines the initial letter of each connector: if it is 'z', then the usual pruning rules no longer apply, and one or more phantom words are selected out of the bucket of phantom words. (This bucket is kept out-of-line, it is not yet placed into sentence word sequence order, which is why the usual pruning rules get modified.) Otherwise, parsing continues as normal. At the end of parsing, if there are any phantom words that are linked, then all of the connectors on the disjunct must be satisfied (of course!) else the linkage is invalid. After parsing, the phantom words can be inserted into the sentence, with the location deduced from link lengths.
A more principled approach to fixing the phantom-word issue is to borrow the idea of re-writing from the theory of operator grammar. That is, certain phrases and constructions can be (should be) re-written into their "proper form", prior to parsing. The re-writing step would insert the missing words, then the parsing proceeds. One appeal of such an approach is that re-writing can also handle other "annoying" phenomena, such as typos (missing apostrophes, eg "lets" vs. "let's", "its" vs. "it's") as well as multi-word rewrites (eg "let's" vs. "let us", or "it's" vs. "it is").
Exactly how to implement this is unclear. However, it seems to open the door to more abstract, semantic analysis. Thus, for example, in Meaning-Text Theory (MTT), one must move between SSynt to DSynt structures. Such changes require a graph re-write from the surface syntax parse (eg provided by link-grammar) to the deep-syntactic structure. By contrast, handling phantom words by graph re-writing prior to parsing inverts the order of processing. This suggests that a more holistic approach is needed to graph rewriting: it must somehow be performed "during" parsing, so that parsing can both guide the insertion of the phantom words, and, simultaneously guide the deep syntactic rewrites.
Another interesting possibility arises with regards to tokenization. The current tokenizer is clever, in that it splits not only on whitespace, but can also strip off prefixes, suffixes, and perform certain limited kinds of morphological splitting. That is, it currently has the ability to re-write single-words into sequences of words. It currently does so in a conservative manner; the letters that compose a word are preserved, with a few exceptions, such as making spelling correction suggestions. The above considerations suggest that the boundary between tokenization and parsing needs to become both more fluid, and more tightly coupled.
Compare "she will be happier than before" to "she will be more happy than before." Current parser makes "happy" the head word, and "more" a modifier w/EA link. I believe the correct solution would be to make "more" the head (link it as a comparative), and make "happy" the dependent. This would harmonize rules for comparatives... and would eliminate/simplify rules for less,more.
However, this idea needs to be double-checked against, eg Hudson's word grammar. I'm confused on this issue ...
Currently, some links can act at "unlimited" length, while others can only be finite-length. eg determiners should be near the noun that they apply to. A better solution might be to employ a 'stretchiness' cost to some connectors: the longer they are, the higher the cost. (This eliminates the "unlimited_connector_set" in the dictionary).
Sometimes, the existence of one parse should suggest that another parse must surely be wrong: if one parse is possible, then the other parses must surely be unlikely. For example: the conjunction and.jg allows the "The Great Southern and Western Railroad" to be parsed as the single name of an entity. However, it also provides a pattern match for "John and Mike" as a single entity, which is almost certainly wrong. But "John and Mike" has an alternative parse, as a conventional-and -- a list of two people, and so the existence of this alternative (and correct) parse suggests that perhaps the entity-and is really very much the wrong parse. That is, the mere possibility of certain parses should strongly disfavor other possible parses. (Exception: Ben & Jerry's ice cream; however, in this case, we could recognize Ben & Jerry as the name of a proper brand; but this is outside of the "normal" dictionary (?) (but maybe should be in the dictionary!))
More examples: "high water" can have the connector A joining high.a and AN joining high.n; these two should either be collapsed into one, or one should be eliminated.
Use WordNet to reduce the number for parses for sentences containing compound verb phrases, such as "give up", "give off", etc.
To avoid a combinatorial explosion of parses, it would be nice to have an incremental parsing, phrase by phrase, using a sliding window algorithm to obtain the parse. Thus, for example, the parse of the last half of a long, run-on sentence should not be sensitive to the parse of the beginning of the sentence.
Doing so would help with combinatorial explosion. So, for example, if the first half of a sentence has 4 plausible parses, and the last half has 4 more, then currently, the parser reports 16 parses total. It would be much more useful if it could instead report the factored results: ie the four plausible parses for the first half, and the four plausible parses for the last half. This would ease the burden on downstream users of link-grammar.
This approach has at psychological support. Humans take long sentences and split them into smaller chunks that "hang together" as phrase- structures, viz compounded sentences. The most likely parse is the one where each of the quasi sub-sentences is parsed correctly.
This could be implemented by saving dangling right-going connectors into a parse context, and then, when another sentence fragment arrives, use that context in place of the left-wall.
This somewhat resembles the application of construction grammar ideas to the link-grammar dictionary. It also somewhat resembles Viterbi parsing to some fixed depth. Verbigracia. do a full backward-forward parse for a phrase, and then, once this is done, take a Viterbi-step. That is, once the phrase is done, keep only the dangling connectors to the phrase, place a wall, and then step to the next part of the sentence.
Caution: watch out for garden-path sentences:
The horse raced past the barn fell.
The old man the boat.
The cotton clothing is made of grows in Mississippi.
The current parser parses these perfectly; a viterbi parser could trip on these.
Other benefits of a Viterbi decoder:
One may argue that Viterbi is a more natural, biological way of working with sequences. Some experimental, psychological support for this can be found at http://www.sciencedaily.com/releases/2012/09/120925143555.htm per Morten Christiansen, Cornell professor of psychology.
Consider the sentence "Thieves rob bank" -- a typical newspaper headline. LG currently fails to parse this, because the determiner is missing ("bank" is a count noun, not a mass noun, and thus requires a determiner. By contrast, "thieves rob water" parses just fine.) A fix for this would be to replace mandatory determiner links by (D- or {[[()]] & headline-flag}) which allows the D link to be omitted if the headline-flag bit is set. Here, "headline-flag" could be a new link-type, but one that is not subject to planarity constraints.
Note that this is easier said than done: if one simply adds a high-cost null link, and no headline-flag, then all sorts of ungrammatical sentences parse, with strange parses; while some grammatical sentences, which should parse, but currently don't, become parsable, but with crazy results.
More examples, from And Rosta:
"when boy meets girl"
"when bat strikes ball"
"both mother and baby are well"
A natural approach would be to replace fixed costs by formulas. This would allow the dialect/sociolect to be dynamically changeable. That is, rather than having a binary headline-flag, there would be a formula for the cost, which could be changed outside of the parsing loop. Such formulas could be used to enable/disable parsing specific to different dialects/sociolects, simply by altering the network of link costs.
A simpler alternative would be to have labeled costs (a cost vector), so that different dialects assign different costs to various links. A dialect would be specified during the parse, thus causing the costs for that dialect to be employed during parse ranking.
This has been implemented; what's missing is a practical tutorial on how this might be used.
A good reference for refining verb usage patterns is: "COBUILD GRAMMAR PATTERNS 1: VERBS from THE COBUILD SERIES", from THE BANK OF ENGLISH, HARPER COLLINS. Online at https://arts-ccr-002.bham.ac.uk/ccr/patgram/ and http://www.corpus.bham.ac.uk/publications/index.shtml
Currently tokenize.c tokenizes double-quotes and some UTF8 quotes (see the RPUNC/LPUNC class in en/4.0.affix - the QUOTES class is not used for that, but for capitalization support), with some very basic support in the English dictionary (see "% Quotation marks." there). However, it does not do this for the various "curly" UTF8 quotes, such as 'these' and “these”. This results is some ugly parsing for sentences containing such quotes. (Note that these are in 4.0.affix).
A mechanism is needed to disentangle the quoting from the quoted text, so that each can be parsed appropriately. It's somewhat unclear how to handle this within link-grammar. This is somewhat related to the problem of morphology (parsing words as if they were "mini-sentences",) idioms (phrases that are treated as if they were single words), set-phrase structures (if ... then ... not only... but also ...) which have a long-range structure similar to quoted text (he said ...).
See also GitHub issue #42.
"to be fishing": Link grammar offers four parses of "I was fishing for evidence", two of which are given low scores, and two are given high scores. Of the two with high scores, one parse is clearly bad. Its links "to be fishing.noun" as opposed to the correct "to be fishing.gerund". That is, I can be happy, healthy and wise, but I certainly cannot be fishing.noun. This is perhaps not just a bug in the structure of the dictionary, but is perhaps deeper: link-grammar has little or no concept of lexical units (ie collocations, idioms, institutional phrases), which thus allows parses with bad word-senses to sneak in.
The goal is to introduce more knowledge of lexical units into LG.
Different word senses can have different grammar rules (and thus, the links employed reveal the sense of the word): for example: "I tend to agree" vs. "I tend to the sheep" -- these employ two different meanings for the verb "tend", and the grammatical constructions allowed for one meaning are not the same as those allowed for the other. Yet, the link rules for "tend.v" have to accommodate both senses, thus making the rules rather complex. Worse, it potentially allows for non-sense constructions. If, instead, we allowed the dictionary to contain different rules for "tend.meaning1" and "tend.meaning2", the rules would simplify (at the cost of inflating the size of the dictionary).
Another example: "I fear so" -- the word "so" is only allowed with some, but not all, lexical senses of "fear". So eg "I fear so" is in the same semantic class as "I think so" or "I hope so", although other meanings of these verbs are otherwise quite different.
[Sin2004] "New evidence, new priorities, new attitudes" in J. Sinclair, (ed) (2004) How to use corpora in language teaching, Amsterdam: John Benjamins
See also: Pattern Grammar: A Corpus-Driven Approach to the Lexical Grammar of English
Susan Hunston and Gill Francis (University of Birmingham)
Amsterdam: John Benjamins (Studies in corpus linguistics, edited by Elena Tognini-Bonelli, volume 4), 2000
Book review.
“The Molecular Level of Lexical Semantics”, EA Nida, (1997) International Journal of Lexicography, 10(4): 265–274. En línea
The link-grammar provides several mechanisms to support circumpositions or even more complicated multi-word structures. One mechanism is by ordinary links; see the V, XJ and RJ links. The other mechanism is by means of post-processing rules. (For example, the "filler-it" SF rules use post-processing.) However, rules for many common forms have not yet been written. The general problem is of supporting structures that have "holes" in the middle, that require "lacing" to tie them together.
For a general theory, see catena.
For example, the adposition:
... from [xxx] on.
"He never said another word from then on."
"I promise to be quiet from now on."
"Keep going straight from that point on."
"We went straight from here on."
... from there on.
"We went straight, from the house on to the woods."
"We drove straight, from the hill onwards."
Note that multiple words can fit in the slot [xxx]. Note the tangling of another prepositional phrase: "... from [xxx] on to [yyy]"
More complicated collocations with holes include
"First.. next..."
"If ... then ..."
'Then' is optional ('then' is a 'null word'), for example:
"If it is raining, stay inside!"
"If it is raining, [then] stay inside!"
"if ... only ..." "If there were only more like you!"
"... not only, ... but also ..."
"As ..., so ..." "As it was commanded, so it shall be done"
"Either ... or ..."
"Both ... and ..." "Both June and Tom are coming"
"ought ... if ..." "That ought to be the case, if John is not lying"
"Someone ... who ..."
"Someone is outside who wants to see you"
"... for ... to ..."
"I need for you to come to my party"
The above are not currently supported. An example that is supported is the "non-referential it", eg
"It ... that ..."
"It seemed likely that John would go"
The above is supported by means of special disjuncts for 'it' and 'that', which must occur in the same post-processing domain.
Ver también:
http://www.phon.ucl.ac.uk/home/dick/enc2010/articles/extraposition.htm
http://www.phon.ucl.ac.uk/home/dick/enc2010/articles/relative-clause.htm
"...from X and from Y" "By X, and by Y, ..." Here, X and Y might be rather long phrases, containing other prepositions. In this case, the usual link-grammar linkage rules will typically conjoin "and from Y" to some preposition in X, instead of the correct link to "from X". Although adding a cost to keep the lengths of X and Y approximately equal can help, it would be even better to recognize the "...from ... and from..." pattern.
The correct solution for the "Either ... or ..." appears to be this:
---------------------------+---SJrs--+
+------???----------+ |
| +Ds**c+--SJls-+ +Ds**+
| | | | | |
either.r the lorry.n or.j-n the van.n
The wrong solution is
--------------------------+
+-----Dn-----+ +---SJrs---+
| +Ds**c+--SJn--+ +Ds**+
| | | | | |
neither.j the lorry.n nor.j-n the van.n
The problem with this is that "neither" must coordinate with "nor". That is, one cannot say "either.. nor..." "neither ... or ... " "neither ...and..." "but ... nor ..." The way I originally solved the coordination problem was to invent a new link called Dn, and a link SJn and to make sure that Dn could only connect to SJn, and nothing else. Thus, the lower-case "n" was used to propagate the coordination across two links. This demonstrates how powerful the link-grammar theory is: with proper subscripts, constraints can be propagated along links over large distances. However, this also makes the dictionary more complex, and the rules harder to write: coordination requires a lot of different links to be hooked together. And so I think that creating a single, new link, called ???, will make the coordination easy and direct. That is why I like that idea.
El ??? link should be the XJ link, which-see.
More idiomatic than the above examples: "...the chip on X's shoulder" "to do X a favour" "to give X a look"
The above are all examples of "set phrases" or "phrasemes", and are most commonly discussed in the context of MTT or Meaning-Text Theory of Igor Mel'cuk et al (search for "MTT Lexical Function" for more info). Mel'cuk treats set phrases as lexemes, and, for parsing, this is not directly relevant. However, insofar as phrasemes have a high mutual information content, they can dominate the syntactic structure of a sentence.
The current parse of "he wanted to look at and listen to everything." is inadequate: the link to "everything" needs to connect to "and", so that "listen to" and "look at" are treated as atomic verb phrases.
MTT suggests that perhaps the correct way to understand the contents of the post-processing rules is as an implementation of 'lexical functions' projected onto syntax. That is, the post-processing rules allow only certain syntactical constructions, and these are the kinds of constructions one typically sees in certain kinds of lexical functions.
Alternately, link-grammar suffers from a combinatoric explosion of possible parses of a given sentence. It would seem that lexical functions could be used to rule out many of these parses. On the other hand, the results are likely to be similar to that of statistical parse ranking (which presumably captures such quasi-idiomatic collocations at least weakly).
Árbitro. I. Mel'cuk: "Collocations and Lexical Functions", in ''Phraseology: theory, analysis, and applications'' Ed. Anthony Paul Cowie (1998) Oxford University Press pp. 23-54.
More generally, all of link-grammar could benefit from a MTT-izing of infrastructure.
Compare the above commentary on lexical functions to Hebrew morphological analysis. To quote Wikipedia:
This distinction between the word as a unit of speech and the root as a unit of meaning is even more important in the case of languages where roots have many different forms when used in actual words, as is the case in Semitic languages. In these, roots are formed by consonants alone, and different words (belonging to different parts of speech) are derived from the same root by inserting vowels. For example, in Hebrew, the root gdl represents the idea of largeness, and from it we have gadol and gdola (masculine and feminine forms of the adjective "big"), gadal "he grew", higdil "he magnified" and magdelet "magnifier", along with many other words such as godel "size" and migdal "tower".
Instead of hard-coding LL, declare which links are morpho links in the dict.
Version 6.0 will change Sentence to Sentence*, Linkage to Linkage* in the API. But perhaps this is a bad idea...