awk - 匹配一列并返回一些其他列,如 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 中导入它们。
解决方案
使用 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
推荐阅读
- android - 如何执行一个动画然后另一个
- scala - Scala .map() 信息丢失(因为返回类型与元素相同:Set)
- android - 出现错误:创建 Google Maps Activity 项目后清单合并失败
- java - AsyncHttpClient 不会让程序退出
- javascript - 为什么 $data 引用在此示例中不起作用?
- linux - Makefile:138:TooN、libCVD 和 Gvars3 安装中目标“全部”的配方失败错误
- python - 在我自己创建的函数周围包裹一个 pandas 函数
- acumatica - 如何将通配符附加到 DAC 字段的子字符串?
- search - Grep 获取字符串并读取内容,直到下一个匹配字符串
- css - 如何更改单个垫子步骤图标的背景颜色?