首页 > 解决方案 > 匹配一列并返回一些其他列,如 sql

问题描述

如何将语料库文件与词干中的第二列匹配并返回第一列?

corpus.txt
this
is
broken
testing
as
told

此文件中只有前 2 列是重要的:

stem.csv

"test";"tested";"test";"Suffix";"A";"7673";"321: 0 xxx"
"test";"testing";"test";"Suffix";"A";"7673";"322: 0 xxx"
"test";"tests";"test";"Suffix";"b";"5942";"001: 0 xxx"
"break";"broke";"break";"Suffix";"b";"5942";"002: 0 xxx"
"break";"broken";"break";"Suffix";"b";"5942";"003: 0 xxx"
"break";"breaks";"break";"Suffix";"c";"5778";"001: 0 xxx"
"tell";"told";"tell";"Suffix";"c";"5778";"002: 0 xx"

如果词干文件中缺少该单词,则应将其替换为XXX

expected.txt

XXX
XXX
break
test
XXX
tell

可以使用这样的 SQL 查询来完成...

CREATE TABLE `stem` (
  `column1` varchar(100) DEFAULT NULL,
  `column2` varchar(100) DEFAULT NULL
) ;

INSERT INTO `stem` VALUES ('break','broken'),('break','breaks'),('test','tests');

CREATE TABLE `corpus` (
  `column1` varchar(100) DEFAULT NULL
) 

INSERT INTO `corpus` VALUES ('tests'),('xyz');
_____

    mysql> select ifnull(b.column1, 'XXX') as result from corpus as a left join stem as b on a.column1 = b.column2;
    +--------+
    | result |
    +--------+
    | test   |
    | XXX    |
    +--------+

但我正在寻找一种直接处理文本文件的方法,这样我就不需要在 mysql 中导入它们。

标签: awksedgrep

解决方案


使用 awk:

$ awk -F';' '          # delimiter
NR==FNR {             # process the stem file
    gsub(/"/,"")      # off with the double quotes
    a[$2]=$1          # hash
    next
}
{
    if($1 in a)       # if corpus entry found in stem
        print a[$1]   # output
    else 
        print "XXX"
}' stem corpus 

输出:

XXX
XXX
break
test
XXX
tell

推荐阅读