4

考虑以下两个略有不同的文件:

foo(旧版):

<Line 1> a
<Line 2> b
<Line 3> c
<Line 4> d

foo(新版本):

<Line 1> a
<Line 2> e
<Line 3> b
<Line 4> c
<Line 5> f
<Line 6> d

如您所见,新文件中引入了字符e和。f

我有一组对应于旧文件的行号……比如,、、134对应于字母a、、cd)。

有没有办法在这两个文件之间进行映射,以便我可以获得新文件中相应字符的行号?

EG,结果将是:

Old file line numbers (1,3,4) ===> New File line numbers (1,4,6)

不幸的是,我只有 emacs(带有工作 ediff)、Python 和 winmerge 可供我使用。

4

2 回答 2

3

您可以在 Emacs 中完成所有操作:

(defun get-joint-index (file-a index file-b)
  (let ((table (make-hash-table :test #'equal)))
    (flet ((line () (buffer-substring-no-properties
                     (point-at-bol) (point-at-eol))))
      (with-temp-buffer (insert-file file-b)
        (loop for i from 1 do (puthash (line) i table)
              while (zerop (forward-line))))
      (with-temp-buffer (insert-file file-a)
        (loop for i in index do (goto-line i)
              collect (gethash (line) table))))))

跑步,

M-:(get-joint-index "/tmp/old" '(1 3 4) "/tmp/new")

->(1 4 6)

于 2011-12-01T08:49:44.850 回答
2

您需要的是一个字符串搜索算法,您需要在文本(新版本的 foo)中搜索多个模式(来自旧版本 foo 的行)。Rabin-Karp算法就是用于此类任务的一种算法。我已经根据您的问题对其进行了调整:

def linematcher(haystack, needles, lineNumbers):
    f = open(needles)
    needles = [line.strip() for n, line in enumerate(f, 1) if n in lineNumbers]
    f.close()

    hsubs = set(hash(s) for s in needles)
    for n, lineWithNewline in enumerate(open(haystack), 1):
        line = lineWithNewline.strip()
        hs = hash(line)
        if hs in hsubs and line in needles:
            print "{0} ===> {1}".format(lineNumbers[needles.index(line)], n)

假设你的两个文件被调用old_foo.txtnew_foo.txt然后你会这样调用这个函数:

linematcher('new_foo.txt', 'old_foo.txt', [1, 3, 4])

当我尝试使用您的数据时,它会打印:

1 ===> 1
3 ===> 4
4 ===> 6
于 2011-12-01T06:42:36.023 回答