python - 发现相似文件中的不同行

标签 python bash awk

我有一个文本文件,其中包含数以万计的短句子,如下所示:

go to venice
come back from grece
new york here i come
from belgium to russia and back to spain

我运行一个标记算法,该算法会生成该句子文件的标记输出:

go to <place>venice</place>
come back from <place>grece</place>
<place>new york</place> here i come
from <place>belgium</place> to <place>russia</place> and back to <place>spain</place>

该算法多次对输入运行,并每次生成略有不同的标记。我的目标是找出发生这些差异的线路。换句话说,打印 N 个结果文件中标记不同的所有话语。

例如 N=10,我得到 10 个标记文件。假设第 1 行对于所有 10 个标记文件始终标记为相同 - 不打印它。假设第 2 行以这种方式标记一次,以其他方式标记 9 次 - 打印它。等等。

对于 N=2 很简单,我只需运行 diff 即可。但是如果我有 N=10 个结果该怎么办?

最佳答案

如果您有标记的文件 - 只需为每一行创建一个计数器,记录您看到该文件的次数:

# use defaultdict for convenience
from collections import defaultdict

# start counting at 0
counter_dict = defaultdict(lambda: 0)

tagged_file_names = ['tagged1.txt', 'tagged2.txt', ...]

# add all lines of each file to dict
for file_name in tagged_file_names:
    with open(file_name) as f:
        # use enumerate to maintain order
        # produces (LINE_NUMBER, LINE CONTENT) tuples (hashable)
        for line_with_number in enumerate(f.readlines()):
            counter_dict[line_with_number] += 1

# print all values that do not repeat in all files (in same location)
for key, value in counter_dict.iteritems():
    if value < len(tagged_file_names):
        print "line number %d: [%s] only repeated %d times" % (
            key[0], key[1].strip(), value
        )

演练:

首先,我们创建一个数据结构,使我们能够对条目进行计数,这些条目是编号行。这个数据结构是 collections.defaultdict默认值为 0 - 这是新添加的行数(每次添加都会增加到 1)。

然后,我们使用 tuple 创建实际条目它是可散列的,因此可以用作字典键,并且默认情况下与其他元组可深度比较。这意味着 (1, "lolz") 等于 (1, "lolz") 但不同于 (1, "not lolz")(2, lolz) - 因此它适合我们使用深度比较行来解释内容和位置。

现在剩下要做的就是使用简单的 for 循环添加所有条目,并查看所有文件中出现哪些键(对应于编号行)(也就是说,它们的值等于提供的标记文件数量)。

示例:

reut@tHP-EliteBook-8470p:~/python/counter$ cat tagged1.txt 
123
abc
def
reut@tHP-EliteBook-8470p:~/python/counter$ cat tagged2.txt 
123
def
def
reut@tHP-EliteBook-8470p:~/python/counter$ ./difference_counter.py 
line number 1: [abc] only repeated 1 times
line number 1: [def] only repeated 1 times

关于python - 发现相似文件中的不同行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28444135/

相关文章:

python - 下面的代码片段有什么问题?

bash - 用于将文件从驼峰式转换为下划线的 awk/sed 脚本

bash - 从 Vim 执行 Bash 中的当前行

character-encoding - 在 awk 匹配函数的字符串参数中使用特殊字符。当前区域设置

linux - 获取带问号的行和之前的行 - sed

python - 从python中的csv文件中获取特定列

python - 如何在不使用 try/catch 的情况下测试 Python Enum 中是否存在 int 值?

php - 检测图像是否损坏或损坏

linux - bash脚本: Apache Server is running or not

linux - 最常用IP地址bash脚本的Apache访问日志