【问题标题】:Checking if a set of string in a file are in another file or not using python or bash检查文件中的一组字符串是否在另一个文件中或不使用 python 或 bash
【发布时间】:2017-04-27 10:56:15
【问题描述】:

您好,我想检查一个文件中包含的一组单词(字母数字)是否在另一个包含一组单词的文件中。

就像我有一个文件:f1.txt(20K 大小)

w1
w2
w3
w4
.. //more ids like this

另一个文件 f2.txt(120 K 大小)

q1
q2
q3
q4
q5
q6
q7
q8
w2

所以我想检查“f2.txt”中存在“多少”和“f1.txt”中的“哪些”id

我希望输出是这样的:

1
w2

我知道这很简单,可以使用循环来完成。我想知道我们是否可以使用 bash 脚本来做到这一点,使用“grep”n all。由于这很快,我主要想分析数据。 Python 也可以。

感谢任何潜在客户。

【问题讨论】:

  • awk 可能是最快的方法(除非你用 C 或其他编译语言编写了一些东西),尽管如果你对 f1 数据使用集合,Python 会很快。绝对不要尝试使用解析 f1 并将该数据用于 grep f2 的 Bash 脚本来执行此操作,这会相当慢,而且它是 bad practice to use a shell loop to process text

标签: python linux bash search command-line


【解决方案1】:

由于文件不是很大,我们可以将它们放在内存中(一个 awk 哈希表)进行比较:

awk 'NR==FNR{a[$0];next}$0 in a{a[$0]++}
  END{for(x in a)if(a[x])print x, a[x]}' f1 f2

它输出:

w2 1

(输出只是举例,输出格式可以轻松调整。)

awk                    # the awk cmd
'NR==FNR{a[$0];next}   # take the first file:f1, save in hashtable a[word]=0
$0 in a{a[$0]++}       # take the 2nd file:f2, if word in a hit, increment
END{                   # after two files are processed, we r about to print
   for(x in a)         # go thru the hashtable
    if(a[x])           # if value>0 (the word shows in f2)
     print x, a[x]}'   # we print the which word(key), and how many times(value) 
f1 f2                  # two input files.

【讨论】:

  • 这不适用于我的大型数据集。即使对于不在 f2.txt 中的 id,我也会显示 2。
  • 虽然它适用于上面提供的这个小文件。
【解决方案2】:

你可以使用

str.count(sub[, start[, end]])

返回[start, end] 范围内子字符串sub 的非重叠出现次数。可选参数 startend 被解释为切片表示法。

f1_lines = [line.strip("\n") for line in f1.readlines()]
f2_lines = [line.strip("\n") for line in f2.readlines()]

for w in f1_lines:
    print(w, f2_lines.count(w))

【讨论】:

    猜你喜欢
    • 2014-12-26
    • 2016-04-10
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多