# SOME DESCRIPTIVE TITLE. # Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: # Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2025-07-25 16:03+0000\n" "PO-Revision-Date: 2025-07-18 19:58+0000\n" "Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Chinese (China) (https://app.transifex.com/python-doc/teams/5390/zh_CN/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: zh_CN\n" "Plural-Forms: nplurals=1; plural=0;\n" #: ../../library/difflib.rst:2 msgid ":mod:`!difflib` --- Helpers for computing deltas" msgstr ":mod:`!difflib` --- 计算差异的辅助工具" #: ../../library/difflib.rst:11 msgid "**Source code:** :source:`Lib/difflib.py`" msgstr "**源代码:** :source:`Lib/difflib.py`" #: ../../library/difflib.rst:20 msgid "" "This module provides classes and functions for comparing sequences. It can " "be used for example, for comparing files, and can produce information about " "file differences in various formats, including HTML and context and unified " "diffs. For comparing directories and files, see also, the :mod:`filecmp` " "module." msgstr "" "此模块提供用于比较序列的类和函数。 例如,它可被用于比较文件,并可产生多种格式的不同文件差异信息,包括 HTML 和上下文以及统一的 diff 数据。 " "有关比较目录和文件,另请参阅 :mod:`filecmp` 模块。" #: ../../library/difflib.rst:29 msgid "" "This is a flexible class for comparing pairs of sequences of any type, so " "long as the sequence elements are :term:`hashable`. The basic algorithm " "predates, and is a little fancier than, an algorithm published in the late " "1980's by Ratcliff and Obershelp under the hyperbolic name \"gestalt pattern" " matching.\" The idea is to find the longest contiguous matching " "subsequence that contains no \"junk\" elements; these \"junk\" elements are " "ones that are uninteresting in some sense, such as blank lines or " "whitespace. (Handling junk is an extension to the Ratcliff and Obershelp " "algorithm.) The same idea is then applied recursively to the pieces of the " "sequences to the left and to the right of the matching subsequence. This " "does not yield minimal edit sequences, but does tend to yield matches that " "\"look right\" to people." msgstr "" "这是一个灵活的类,可用于比较任何类型的序列对,只要序列元素为 :term:`hashable` 对象。 其基本算法要早于由 Ratcliff 和 " "Obershelp 于 1980 年代末期发表并以“格式塔模式匹配”的夸张名称命名的算法,并且更加有趣一些。 " "其思路是找到不包含“垃圾”元素的最长连续匹配子序列;所谓“垃圾”元素是指其在某种意义上没有价值,例如空白行或空白符。 (处理垃圾元素是对 " "Ratcliff 和 Obershelp 算法的一个扩展。) 然后同样的思路将递归地应用于匹配序列的左右序列片段。 " "这并不能产生最小编辑序列,但确实能产生在人们看来“正确”的匹配。" #: ../../library/difflib.rst:41 msgid "" "**Timing:** The basic Ratcliff-Obershelp algorithm is cubic time in the " "worst case and quadratic time in the expected case. :class:`SequenceMatcher`" " is quadratic time for the worst case and has expected-case behavior " "dependent in a complicated way on how many elements the sequences have in " "common; best case time is linear." msgstr "" "**耗时:** 基本 Ratcliff-Obershelp 算法在最坏情况下为立方时间而在一般情况下为平方时间。 " ":class:`SequenceMatcher` " "在最坏情况下为平方时间而在一般情况下的行为受到序列中有多少相同元素这一因素的微妙影响;在最佳情况下则为线性时间。" #: ../../library/difflib.rst:47 msgid "" "**Automatic junk heuristic:** :class:`SequenceMatcher` supports a heuristic " "that automatically treats certain sequence items as junk. The heuristic " "counts how many times each individual item appears in the sequence. If an " "item's duplicates (after the first one) account for more than 1% of the " "sequence and the sequence is at least 200 items long, this item is marked as" " \"popular\" and is treated as junk for the purpose of sequence matching. " "This heuristic can be turned off by setting the ``autojunk`` argument to " "``False`` when creating the :class:`SequenceMatcher`." msgstr "" "**自动垃圾启发式计算:** :class:`SequenceMatcher` 支持使用启发式计算来自动将特定序列项视为垃圾。 " "这种启发式计算会统计每个单独项在序列中出现的次数。 如果某一项(在第一项之后)的重复次数超过序列长度的 1% 并且序列长度至少有 200 " "项,该项会被标记为“热门”并被视为序列匹配中的垃圾。 这种启发式计算可以通过在创建 :class:`SequenceMatcher` 时将 " "``autojunk`` 参数设为 ``False`` 来关闭。" #: ../../library/difflib.rst:55 ../../library/difflib.rst:386 msgid "Added the *autojunk* parameter." msgstr "增加了 *autojunk* 形参。" #: ../../library/difflib.rst:61 msgid "" "This is a class for comparing sequences of lines of text, and producing " "human-readable differences or deltas. Differ uses :class:`SequenceMatcher` " "both to compare sequences of lines, and to compare sequences of characters " "within similar (near-matching) lines." msgstr "" "这个类的作用是比较由文本行组成的序列,并产生可供人阅读的差异或增量信息。 Differ 统一使用 :class:`SequenceMatcher` " "来完成行序列的比较以及相似(接近匹配)行内部字符序列的比较。" #: ../../library/difflib.rst:66 msgid "Each line of a :class:`Differ` delta begins with a two-letter code:" msgstr ":class:`Differ` 增量的每一行均以双字母代码打头:" #: ../../library/difflib.rst:69 msgid "Code" msgstr "双字母代码" #: ../../library/difflib.rst:69 ../../library/difflib.rst:496 msgid "Meaning" msgstr "含意" #: ../../library/difflib.rst:71 msgid "``'- '``" msgstr "``'- '``" #: ../../library/difflib.rst:71 msgid "line unique to sequence 1" msgstr "行为序列 1 所独有" #: ../../library/difflib.rst:73 msgid "``'+ '``" msgstr "``'+ '``" #: ../../library/difflib.rst:73 msgid "line unique to sequence 2" msgstr "行为序列 2 所独有" #: ../../library/difflib.rst:75 msgid "``' '``" msgstr "``' '``" #: ../../library/difflib.rst:75 msgid "line common to both sequences" msgstr "行在两序列中相同" #: ../../library/difflib.rst:77 msgid "``'? '``" msgstr "``'? '``" #: ../../library/difflib.rst:77 msgid "line not present in either input sequence" msgstr "行不存在于任一输入序列" #: ../../library/difflib.rst:80 msgid "" "Lines beginning with '``?``' attempt to guide the eye to intraline " "differences, and were not present in either input sequence. These lines can " "be confusing if the sequences contain whitespace characters, such as spaces," " tabs or line breaks." msgstr "" "以 '``?``' 打头的行尝试将视线紖至行以外而不存在于任一输入序列的差异。 如果序列包含空白符,例如空格、制表或换行则这些行可能会令人感到迷惑。" #: ../../library/difflib.rst:87 msgid "" "This class can be used to create an HTML table (or a complete HTML file " "containing the table) showing a side by side, line by line comparison of " "text with inter-line and intra-line change highlights. The table can be " "generated in either full or contextual difference mode." msgstr "" "这个类可用于创建 HTML 表格(或包含表格的完整 HTML 文件)以并排地逐行显示文本比较,行间与行外的更改将突出显示。 " "此表格可以基于完全或上下文差异模式来生成。" #: ../../library/difflib.rst:92 msgid "The constructor for this class is:" msgstr "这个类的构造函数:" #: ../../library/difflib.rst:97 msgid "Initializes instance of :class:`HtmlDiff`." msgstr "初始化 :class:`HtmlDiff` 的实例。" #: ../../library/difflib.rst:99 msgid "" "*tabsize* is an optional keyword argument to specify tab stop spacing and " "defaults to ``8``." msgstr "*tabsize* 是一个可选关键字参数,指定制表位的间隔,默认值为 ``8``。" #: ../../library/difflib.rst:102 msgid "" "*wrapcolumn* is an optional keyword to specify column number where lines are" " broken and wrapped, defaults to ``None`` where lines are not wrapped." msgstr "*wrapcolumn* 是一个可选关键字参数,指定行文本自动打断并换行的列位置,默认值为 ``None`` 表示不自动换行。" #: ../../library/difflib.rst:105 msgid "" "*linejunk* and *charjunk* are optional keyword arguments passed into " ":func:`ndiff` (used by :class:`HtmlDiff` to generate the side by side HTML " "differences). See :func:`ndiff` documentation for argument default values " "and descriptions." msgstr "" "*linejunk* 和 *charjunk* 均是可选关键字参数,会传入 :func:`ndiff` (被 :class:`HtmlDiff` " "用来生成并排显示的 HTML 差异)。 请参阅 :func:`ndiff` 文档了解参数默认值及其说明。" #: ../../library/difflib.rst:109 msgid "The following methods are public:" msgstr "下列是公开的方法" #: ../../library/difflib.rst:114 msgid "" "Compares *fromlines* and *tolines* (lists of strings) and returns a string " "which is a complete HTML file containing a table showing line by line " "differences with inter-line and intra-line changes highlighted." msgstr "" "比较 *fromlines* 和 *tolines* (字符串列表) 并返回一个字符串,表示一个完整 HTML " "文件,其中包含各行差异的表格,行间与行外的更改将突出显示。" #: ../../library/difflib.rst:118 msgid "" "*fromdesc* and *todesc* are optional keyword arguments to specify from/to " "file column header strings (both default to an empty string)." msgstr "*fromdesc* 和 *todesc* 均是可选关键字参数,指定来源/目标文件的列标题字符串(默认均为空白字符串)。" #: ../../library/difflib.rst:121 msgid "" "*context* and *numlines* are both optional keyword arguments. Set *context* " "to ``True`` when contextual differences are to be shown, else the default is" " ``False`` to show the full files. *numlines* defaults to ``5``. When " "*context* is ``True`` *numlines* controls the number of context lines which " "surround the difference highlights. When *context* is ``False`` *numlines* " "controls the number of lines which are shown before a difference highlight " "when using the \"next\" hyperlinks (setting to zero would cause the \"next\"" " hyperlinks to place the next difference highlight at the top of the browser" " without any leading context)." msgstr "" "*context* 和 *numlines* 均是可选关键字参数。 当只要显示上下文差异时就将 *context* 设为 ``True``,否则默认值 " "``False`` 为显示完整文件。 *numlines* 默认为 ``5``。 当 *context* 为 ``True`` 时 *numlines*" " 将控制围绕突出显示差异部分的上下文行数。 当 *context* 为 ``False`` 时 *numlines* 将控制在使用 \"next\" " "超链接时突出显示差异部分之前所显示的行数(设为零则会导致 \"next\" 超链接将下一个突出显示差异部分放在浏览器顶端,不添加任何前导上下文)。" #: ../../library/difflib.rst:132 msgid "" "*fromdesc* and *todesc* are interpreted as unescaped HTML and should be " "properly escaped while receiving input from untrusted sources." msgstr "*fromdesc* 和 *todesc* 会被当作未转义的 HTML 来解读,当接收不可信来源的输入时应该适当地进行转义。" #: ../../library/difflib.rst:135 msgid "" "*charset* keyword-only argument was added. The default charset of HTML " "document changed from ``'ISO-8859-1'`` to ``'utf-8'``." msgstr "增加了 *charset* 关键字参数。 HTML 文档的默认字符集从 ``'ISO-8859-1'`` 更改为 ``'utf-8'``。" #: ../../library/difflib.rst:141 msgid "" "Compares *fromlines* and *tolines* (lists of strings) and returns a string " "which is a complete HTML table showing line by line differences with inter-" "line and intra-line changes highlighted." msgstr "" "比较 *fromlines* 和 *tolines* (字符串列表) 并返回一个字符串,表示一个包含各行差异的完整 HTML " "表格,行间与行外的更改将突出显示。" #: ../../library/difflib.rst:145 msgid "" "The arguments for this method are the same as those for the " ":meth:`make_file` method." msgstr "此方法的参数与 :meth:`make_file` 方法的相同。" #: ../../library/difflib.rst:152 msgid "" "Compare *a* and *b* (lists of strings); return a delta (a :term:`generator` " "generating the delta lines) in context diff format." msgstr "比较 *a* 和 *b* (字符串列表);返回上下文差异格式的增量信息 (一个产生增量行的 :term:`generator`)。" #: ../../library/difflib.rst:155 msgid "" "Context diffs are a compact way of showing just the lines that have changed " "plus a few lines of context. The changes are shown in a before/after style." " The number of context lines is set by *n* which defaults to three." msgstr "所谓上下文差异是一种只显示有更改的行再加几个上下文行的紧凑形式。 更改被显示为之前/之后的样式。 上下文行数由 *n* 设定,默认为三行。" #: ../../library/difflib.rst:159 msgid "" "By default, the diff control lines (those with ``***`` or ``---``) are " "created with a trailing newline. This is helpful so that inputs created " "from :func:`io.IOBase.readlines` result in diffs that are suitable for use " "with :func:`io.IOBase.writelines` since both the inputs and outputs have " "trailing newlines." msgstr "" "默认情况下,差异控制行(以 ``***`` or ``---`` 表示)是通过末尾换行符来创建的。 这样做的好处是从 " ":func:`io.IOBase.readlines` 创建的输入将得到适用于 :func:`io.IOBase.writelines` " "的差异信息,因为输入和输出都带有末尾换行符。" #: ../../library/difflib.rst:165 ../../library/difflib.rst:297 msgid "" "For inputs that do not have trailing newlines, set the *lineterm* argument " "to ``\"\"`` so that the output will be uniformly newline free." msgstr "对于没有末尾换行符的输入,应将 *lineterm* 参数设为 ``\"\"``,这样输出内容将统一不带换行符。" #: ../../library/difflib.rst:168 msgid "" "The context diff format normally has a header for filenames and modification" " times. Any or all of these may be specified using strings for *fromfile*, " "*tofile*, *fromfiledate*, and *tofiledate*. The modification times are " "normally expressed in the ISO 8601 format. If not specified, the strings " "default to blanks." msgstr "" "上下文差异格式通常带有一个记录文件名和修改时间的标头。 这些信息的部分或全部可以使用字符串 *fromfile*, *tofile*, " "*fromfiledate* 和 *tofiledate* 来指定。 修改时间通常以 ISO 8601 格式表示。 如果未指定,这些字符串默认为空。" #: ../../library/difflib.rst:194 ../../library/difflib.rst:320 msgid "See :ref:`difflib-interface` for a more detailed example." msgstr "请参阅 :ref:`difflib-interface` 获取更详细的示例。" #: ../../library/difflib.rst:199 msgid "" "Return a list of the best \"good enough\" matches. *word* is a sequence for" " which close matches are desired (typically a string), and *possibilities* " "is a list of sequences against which to match *word* (typically a list of " "strings)." msgstr "" "返回由最佳“近似”匹配构成的列表。 *word* 为一个指定目标近似匹配的序列(通常为字符串),*possibilities* 为一个由用于匹配 " "*word* 的序列构成的列表(通常为字符串列表)。" #: ../../library/difflib.rst:203 msgid "" "Optional argument *n* (default ``3``) is the maximum number of close matches" " to return; *n* must be greater than ``0``." msgstr "可选参数 *n* (默认为 ``3``) 指定最多返回多少个近似匹配; *n* 必须大于 ``0``." #: ../../library/difflib.rst:206 msgid "" "Optional argument *cutoff* (default ``0.6``) is a float in the range [0, 1]." " Possibilities that don't score at least that similar to *word* are ignored." msgstr "" "可选参数 *cutoff* (默认为 ``0.6``) 是一个 [0, 1] 范围内的浮点数。 与 *word* " "相似度得分未达到该值的候选匹配将被忽略。" #: ../../library/difflib.rst:209 msgid "" "The best (no more than *n*) matches among the possibilities are returned in " "a list, sorted by similarity score, most similar first." msgstr "候选匹配中(不超过 *n* 个)的最佳匹配将以列表形式返回,按相似度得分排序,最相似的排在最前面。" #: ../../library/difflib.rst:225 msgid "" "Compare *a* and *b* (lists of strings); return a :class:`Differ`\\ -style " "delta (a :term:`generator` generating the delta lines)." msgstr "" "比较 *a* 和 *b* (字符串列表);返回 :class:`Differ` 形式的增量信息 (一个产生增量行的 " ":term:`generator`)。" #: ../../library/difflib.rst:228 msgid "" "Optional keyword parameters *linejunk* and *charjunk* are filtering " "functions (or ``None``):" msgstr "可选关键字形参 *linejunk* 和 *charjunk* 均为过滤函数 (或为 ``None``):" #: ../../library/difflib.rst:231 msgid "" "*linejunk*: A function that accepts a single string argument, and returns " "true if the string is junk, or false if not. The default is ``None``. There " "is also a module-level function :func:`IS_LINE_JUNK`, which filters out " "lines without visible characters, except for at most one pound character " "(``'#'``) -- however the underlying :class:`SequenceMatcher` class does a " "dynamic analysis of which lines are so frequent as to constitute noise, and " "this usually works better than using this function." msgstr "" "*linejunk*: 此函数接受单个字符串参数,如果其为垃圾字符串则返回真值,否则返回假值。 默认为 ``None``。 此外还有一个模块层级的函数 " ":func:`IS_LINE_JUNK`,它会过滤掉没有可见字符的行,除非该行添加了至多一个井号符 (``'#'``) -- 但是下层的 " ":class:`SequenceMatcher` 类会动态分析哪些行的重复频繁到足以形成噪音,这通常会比使用此函数的效果更好。" #: ../../library/difflib.rst:239 msgid "" "*charjunk*: A function that accepts a character (a string of length 1), and " "returns if the character is junk, or false if not. The default is module-" "level function :func:`IS_CHARACTER_JUNK`, which filters out whitespace " "characters (a blank or tab; it's a bad idea to include newline in this!)." msgstr "" "*charjunk*: 此函数接受一个字符(长度为 1 的字符串),如果其为垃圾字符则返回真值,否则返回假值。 默认为模块层级的函数 " ":func:`IS_CHARACTER_JUNK`,它会过滤掉空白字符(空格符或制表符;但包含换行符可不是个好主意!)。" #: ../../library/difflib.rst:260 msgid "Return one of the two sequences that generated a delta." msgstr "返回两个序列中产生增量的那一个。" #: ../../library/difflib.rst:262 msgid "" "Given a *sequence* produced by :meth:`Differ.compare` or :func:`ndiff`, " "extract lines originating from file 1 or 2 (parameter *which*), stripping " "off line prefixes." msgstr "" "给出一个由 :meth:`Differ.compare` 或 :func:`ndiff` 产生的 *序列*,提取出来自文件 1 或 2 (*which*" " 形参) 的行,去除行前缀。" #: ../../library/difflib.rst:266 msgid "Example:" msgstr "示例:" #: ../../library/difflib.rst:283 msgid "" "Compare *a* and *b* (lists of strings); return a delta (a :term:`generator` " "generating the delta lines) in unified diff format." msgstr "比较 *a* 和 *b* (字符串列表);返回统一差异格式的增量信息 (一个产生增量行的 :term:`generator`)。" #: ../../library/difflib.rst:286 msgid "" "Unified diffs are a compact way of showing just the lines that have changed " "plus a few lines of context. The changes are shown in an inline style " "(instead of separate before/after blocks). The number of context lines is " "set by *n* which defaults to three." msgstr "" "所以统一差异是一种只显示有更改的行再加几个上下文行的紧凑形式。 更改被显示为内联的样式(而不是分开的之前/之后文本块)。 上下文行数由 *n* " "设定,默认为三行。" #: ../../library/difflib.rst:291 msgid "" "By default, the diff control lines (those with ``---``, ``+++``, or ``@@``) " "are created with a trailing newline. This is helpful so that inputs created" " from :func:`io.IOBase.readlines` result in diffs that are suitable for use " "with :func:`io.IOBase.writelines` since both the inputs and outputs have " "trailing newlines." msgstr "" "默认情况下,差异控制行 (以 ``---``, ``+++`` 或 ``@@`` 表示) 是通过末尾换行符来创建的。 这样做的好处是从 " ":func:`io.IOBase.readlines` 创建的输入将得到适用于 :func:`io.IOBase.writelines` " "的差异信息,因为输入和输出都带有末尾换行符。" #: ../../library/difflib.rst:300 msgid "" "The unified diff format normally has a header for filenames and modification" " times. Any or all of these may be specified using strings for *fromfile*, " "*tofile*, *fromfiledate*, and *tofiledate*. The modification times are " "normally expressed in the ISO 8601 format. If not specified, the strings " "default to blanks." msgstr "" "统一的差异格式通常带有一个记录文件名和修改时间的标头。 这些信息的部分或全部可以使用字符串 *fromfile*, *tofile*, " "*fromfiledate* 和 *tofiledate* 来指定。 修改时间通常以 ISO 8601 格式表示。 如果未指定,这些字符串将默认为空。" #: ../../library/difflib.rst:324 msgid "" "Compare *a* and *b* (lists of bytes objects) using *dfunc*; yield a sequence" " of delta lines (also bytes) in the format returned by *dfunc*. *dfunc* must" " be a callable, typically either :func:`unified_diff` or " ":func:`context_diff`." msgstr "" "使用 *dfunc* 比较 *a* 和 *b* (字节串对象列表);产生以 *dfunc* 所返回格式表示的差异行列表(也是字节串)。 *dfunc* " "必须是可调用对象,通常为 :func:`unified_diff` 或 :func:`context_diff`。" #: ../../library/difflib.rst:329 msgid "" "Allows you to compare data with unknown or inconsistent encoding. All inputs" " except *n* must be bytes objects, not str. Works by losslessly converting " "all inputs (except *n*) to str, and calling ``dfunc(a, b, fromfile, tofile, " "fromfiledate, tofiledate, n, lineterm)``. The output of *dfunc* is then " "converted back to bytes, so the delta lines that you receive have the same " "unknown/inconsistent encodings as *a* and *b*." msgstr "" "允许你比较编码未知或不一致的数据。 除 *n* 之外的所有输入都必须为字节串对象而非字符串。 作用方式为无损地将所有输入 (除 *n* 之外) " "转换为字符串,并调用 ``dfunc(a, b, fromfile, tofile, fromfiledate, tofiledate, n, " "lineterm)``。 *dfunc* 的输出会被随即转换回字节串,这样你所得到的增量行将具有与 *a* 和 *b* 相同的未知/不一致编码。" #: ../../library/difflib.rst:340 msgid "" "Return ``True`` for ignorable lines. The line *line* is ignorable if *line*" " is blank or contains a single ``'#'``, otherwise it is not ignorable. Used" " as a default for parameter *linejunk* in :func:`ndiff` in older versions." msgstr "" "对于可忽略的行返回 ``True``。 如果 *line* 为空行或只包含单个 ``'#'`` 则 *line* 行就是可忽略的,否则就是不可忽略的。 " "此函数被用作较旧版本 :func:`ndiff` 中 *linejunk* 形参的默认值。" #: ../../library/difflib.rst:347 msgid "" "Return ``True`` for ignorable characters. The character *ch* is ignorable " "if *ch* is a space or tab, otherwise it is not ignorable. Used as a default" " for parameter *charjunk* in :func:`ndiff`." msgstr "" "对于可忽略的字符返回 ``True``。 字符 *ch* 如果为空格符或制表符则 *ch* 就是可忽略的,否则就是不可忽略的。 此函数被用作 " ":func:`ndiff` 中 *charjunk* 形参的默认值。" #: ../../library/difflib.rst:354 msgid "" "`Pattern Matching: The Gestalt Approach " "`_" msgstr "" "`Pattern Matching: The Gestalt Approach " "`_" #: ../../library/difflib.rst:355 msgid "" "Discussion of a similar algorithm by John W. Ratcliff and D. E. Metzener. " "This was published in `Dr. Dobb's Journal `_ in " "July, 1988." msgstr "" "John W. Ratcliff 和 D. E. Metzener 对于一种类似算法的讨论。 此文于 1988 年 7 月发表于 `Dr. Dobb's" " Journal `_。" #: ../../library/difflib.rst:362 msgid "SequenceMatcher Objects" msgstr "SequenceMatcher 对象" #: ../../library/difflib.rst:364 msgid "The :class:`SequenceMatcher` class has this constructor:" msgstr ":class:`SequenceMatcher` 类具有这样的构造器:" #: ../../library/difflib.rst:369 msgid "" "Optional argument *isjunk* must be ``None`` (the default) or a one-argument " "function that takes a sequence element and returns true if and only if the " "element is \"junk\" and should be ignored. Passing ``None`` for *isjunk* is " "equivalent to passing ``lambda x: False``; in other words, no elements are " "ignored. For example, pass::" msgstr "" "可选参数 *isjunk* 必须为 ``None`` (默认值) 或为接受一个序列元素并当且仅当其为应忽略的“垃圾”元素时返回真值的单参数函数。 传入 " "``None`` 作为 *isjunk* 的值就相当于传入 ``lambda x: False``;也就是说不忽略任何值。 例如,传入::" #: ../../library/difflib.rst:375 msgid "lambda x: x in \" \\t\"" msgstr "lambda x: x in \" \\t\"" #: ../../library/difflib.rst:377 msgid "" "if you're comparing lines as sequences of characters, and don't want to " "synch up on blanks or hard tabs." msgstr "如果你以字符序列的形式对行进行比较,并且不希望区分空格符或硬制表符。" #: ../../library/difflib.rst:380 msgid "" "The optional arguments *a* and *b* are sequences to be compared; both " "default to empty strings. The elements of both sequences must be " ":term:`hashable`." msgstr "可选参数 *a* 和 *b* 为要比较的序列;两者默认为空字符串。 两个序列的元素都必须为 :term:`hashable`。" #: ../../library/difflib.rst:383 msgid "" "The optional argument *autojunk* can be used to disable the automatic junk " "heuristic." msgstr "可选参数 *autojunk* 可用于启用自动垃圾启发式计算。" #: ../../library/difflib.rst:389 msgid "" "SequenceMatcher objects get three data attributes: *bjunk* is the set of " "elements of *b* for which *isjunk* is ``True``; *bpopular* is the set of " "non-junk elements considered popular by the heuristic (if it is not " "disabled); *b2j* is a dict mapping the remaining elements of *b* to a list " "of positions where they occur. All three are reset whenever *b* is reset " "with :meth:`set_seqs` or :meth:`set_seq2`." msgstr "" "SequenceMatcher 对象接受三个数据属性: *bjunk* 是 *b* 当中 *isjunk* 为 ``True`` " "的元素集合;*bpopular* 是被启发式计算(如果其未被禁用)视为热门候选的非垃圾元素集合;*b2j* 是将 *b* " "当中剩余元素映射到一个它们出现位置列表的字典。 所有三个数据属性将在 *b* 通过 :meth:`set_seqs` 或 " ":meth:`set_seq2` 重置时被重置。" #: ../../library/difflib.rst:396 msgid "The *bjunk* and *bpopular* attributes." msgstr "*bjunk* 和 *bpopular* 属性。" #: ../../library/difflib.rst:399 msgid ":class:`SequenceMatcher` objects have the following methods:" msgstr ":class:`SequenceMatcher` 对象具有以下方法:" #: ../../library/difflib.rst:403 msgid "Set the two sequences to be compared." msgstr "设置要比较的两个序列。" #: ../../library/difflib.rst:405 msgid "" ":class:`SequenceMatcher` computes and caches detailed information about the " "second sequence, so if you want to compare one sequence against many " "sequences, use :meth:`set_seq2` to set the commonly used sequence once and " "call :meth:`set_seq1` repeatedly, once for each of the other sequences." msgstr "" ":class:`SequenceMatcher` 计算并缓存有关第二个序列的详细信息,这样如果你想要将一个序列与多个序列进行比较,可使用 " ":meth:`set_seq2` 一次性地设置该常用序列并重复地对每个其他序列各调用一次 :meth:`set_seq1`。" #: ../../library/difflib.rst:413 msgid "" "Set the first sequence to be compared. The second sequence to be compared " "is not changed." msgstr "设置要比较的第一个序列。 要比较的第二个序列不会改变。" #: ../../library/difflib.rst:419 msgid "" "Set the second sequence to be compared. The first sequence to be compared " "is not changed." msgstr "设置要比较的第二个序列。 要比较的第一个序列不会改变。" #: ../../library/difflib.rst:425 msgid "Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``." msgstr "找出 ``a[alo:ahi]`` 和 ``b[blo:bhi]`` 中的最长匹配块。" #: ../../library/difflib.rst:427 msgid "" "If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns " "``(i, j, k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo " "<= i <= i+k <= ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j', " "k')`` meeting those conditions, the additional conditions ``k >= k'``, ``i " "<= i'``, and if ``i == i'``, ``j <= j'`` are also met. In other words, of " "all maximal matching blocks, return one that starts earliest in *a*, and of " "all those maximal matching blocks that start earliest in *a*, return the one" " that starts earliest in *b*." msgstr "" "如果 *isjunk* 被省略或为 ``None``,:meth:`find_longest_match` 将返回 ``(i, j, k)`` 使得 " "``a[i:i+k]`` 等于 ``b[j:j+k]``,其中 ``alo <= i <= i+k <= ahi`` 并且 ``blo <= j <= " "j+k <= bhi``。 对于所有满足这些条件的 ``(i', j', k')``,如果 ``i == i'``, ``j <= j'`` " "也被满足,则附加条件 ``k >= k'``, ``i <= i'``。 换句话说,对于所有最长匹配块,返回在 *a* 当中最先出现的一个,而对于在 " "*a* 当中最先出现的所有最长匹配块,则返回在 *b* 当中最先出现的一个。" #: ../../library/difflib.rst:440 msgid "" "If *isjunk* was provided, first the longest matching block is determined as " "above, but with the additional restriction that no junk element appears in " "the block. Then that block is extended as far as possible by matching " "(only) junk elements on both sides. So the resulting block never matches on " "junk except as identical junk happens to be adjacent to an interesting " "match." msgstr "" "如果提供了 *isjunk*,将按上述规则确定第一个最长匹配块,但额外附加不允许块内出现垃圾元素的限制。 " "然后将通过(仅)匹配两边的垃圾元素来尽可能地扩展该块。 这样结果块绝对不会匹配垃圾元素,除非同样的垃圾元素正好与有意义的匹配相邻。" #: ../../library/difflib.rst:447 msgid "" "Here's the same example as before, but considering blanks to be junk. That " "prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the " "second sequence directly. Instead only the ``'abcd'`` can match, and " "matches the leftmost ``'abcd'`` in the second sequence:" msgstr "" "这是与之前相同的例子,但是将空格符视为垃圾。 这将防止 ``' abcd'`` 直接与第二个序列末尾的 ``' abcd'`` 相匹配。 而只可以匹配 " "``'abcd'``,并且是匹配第二个序列最左边的 ``'abcd'``:" #: ../../library/difflib.rst:456 msgid "If no blocks match, this returns ``(alo, blo, 0)``." msgstr "如果未找到匹配块,此方法将返回 ``(alo, blo, 0)``。" #: ../../library/difflib.rst:458 msgid "This method returns a :term:`named tuple` ``Match(a, b, size)``." msgstr "此方法将返回一个 :term:`named tuple` ``Match(a, b, size)``。" #: ../../library/difflib.rst:460 msgid "Added default arguments." msgstr "加入默认参数。" #: ../../library/difflib.rst:466 msgid "" "Return list of triples describing non-overlapping matching subsequences. " "Each triple is of the form ``(i, j, n)``, and means that ``a[i:i+n] == " "b[j:j+n]``. The triples are monotonically increasing in *i* and *j*." msgstr "" "返回描述非重叠匹配子序列的三元组列表。 每个三元组的形式为 ``(i, j, n)``,其含义为 ``a[i:i+n] == b[j:j+n]``。 " "这些三元组按 *i* 和 *j* 单调递增排列。" #: ../../library/difflib.rst:471 msgid "" "The last triple is a dummy, and has the value ``(len(a), len(b), 0)``. It " "is the only triple with ``n == 0``. If ``(i, j, n)`` and ``(i', j', n')`` " "are adjacent triples in the list, and the second is not the last triple in " "the list, then ``i+n < i'`` or ``j+n < j'``; in other words, adjacent " "triples always describe non-adjacent equal blocks." msgstr "" "最后一个三元组用于占位,其值为 ``(len(a), len(b), 0)``。 它是唯一 ``n == 0`` 的三元组。 如果 ``(i, j, " "n)`` 和 ``(i', j', n')`` 是在列表中相邻的三元组,且后者不是列表中的最后一个三元组,则 ``i+n < i'`` 或 ``j+n " "< j'``;换句话说,相邻的三元组总是描述非相邻的相等块。" #: ../../library/difflib.rst:479 msgid "" ">>> s = SequenceMatcher(None, \"abxcd\", \"abcd\")\n" ">>> s.get_matching_blocks()\n" "[Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]" msgstr "" ">>> s = SequenceMatcher(None, \"abxcd\", \"abcd\")\n" ">>> s.get_matching_blocks()\n" "[Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]" #: ../../library/difflib.rst:488 msgid "" "Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is " "of the form ``(tag, i1, i2, j1, j2)``. The first tuple has ``i1 == j1 == " "0``, and remaining tuples have *i1* equal to the *i2* from the preceding " "tuple, and, likewise, *j1* equal to the previous *j2*." msgstr "" "返回描述如何将 *a* 变为 *b* 的 5 元组列表,每个元组的形式为 ``(tag, i1, i2, j1, j2)``。 在第一个元组中 ``i1" " == j1 == 0``,而在其余的元组中 *i1* 等于前一个元组的 *i2*,并且 *j1* 也等于前一个元组的 *j2*。" #: ../../library/difflib.rst:493 msgid "The *tag* values are strings, with these meanings:" msgstr "*tag* 值为字符串,其含义如下:" #: ../../library/difflib.rst:496 msgid "Value" msgstr "值" #: ../../library/difflib.rst:498 msgid "``'replace'``" msgstr "``'replace'``" #: ../../library/difflib.rst:498 msgid "``a[i1:i2]`` should be replaced by ``b[j1:j2]``." msgstr "``a[i1:i2]`` 应由 ``b[j1:j2]`` 替换。" #: ../../library/difflib.rst:501 msgid "``'delete'``" msgstr "``'delete'``" #: ../../library/difflib.rst:501 msgid "``a[i1:i2]`` should be deleted. Note that ``j1 == j2`` in this case." msgstr "``a[i1:i2]`` 应被删除。 请注意在此情况下 ``j1 == j2``。" #: ../../library/difflib.rst:504 msgid "``'insert'``" msgstr "``'insert'``" #: ../../library/difflib.rst:504 msgid "" "``b[j1:j2]`` should be inserted at ``a[i1:i1]``. Note that ``i1 == i2`` in " "this case." msgstr "``b[j1:j2]`` 应插入到 ``a[i1:i1]``。 请注意在此情况下 ``i1 == i2``。" #: ../../library/difflib.rst:508 msgid "``'equal'``" msgstr "``'equal'``" #: ../../library/difflib.rst:508 msgid "``a[i1:i2] == b[j1:j2]`` (the sub-sequences are equal)." msgstr "``a[i1:i2] == b[j1:j2]`` (两个子序列相同)。" #: ../../library/difflib.rst:512 msgid "For example::" msgstr "例如:" #: ../../library/difflib.rst:514 msgid "" ">>> a = \"qabxcd\"\n" ">>> b = \"abycdf\"\n" ">>> s = SequenceMatcher(None, a, b)\n" ">>> for tag, i1, i2, j1, j2 in s.get_opcodes():\n" "... print('{:7} a[{}:{}] --> b[{}:{}] {!r:>8} --> {!r}'.format(\n" "... tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2]))\n" "delete a[0:1] --> b[0:0] 'q' --> ''\n" "equal a[1:3] --> b[0:2] 'ab' --> 'ab'\n" "replace a[3:4] --> b[2:3] 'x' --> 'y'\n" "equal a[4:6] --> b[3:5] 'cd' --> 'cd'\n" "insert a[6:6] --> b[5:6] '' --> 'f'" msgstr "" ">>> a = \"qabxcd\"\n" ">>> b = \"abycdf\"\n" ">>> s = SequenceMatcher(None, a, b)\n" ">>> for tag, i1, i2, j1, j2 in s.get_opcodes():\n" "... print('{:7} a[{}:{}] --> b[{}:{}] {!r:>8} --> {!r}'.format(\n" "... tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2]))\n" "delete a[0:1] --> b[0:0] 'q' --> ''\n" "equal a[1:3] --> b[0:2] 'ab' --> 'ab'\n" "replace a[3:4] --> b[2:3] 'x' --> 'y'\n" "equal a[4:6] --> b[3:5] 'cd' --> 'cd'\n" "insert a[6:6] --> b[5:6] '' --> 'f'" #: ../../library/difflib.rst:529 msgid "Return a :term:`generator` of groups with up to *n* lines of context." msgstr "返回一个带有最多 *n* 行上下文的分组的 :term:`generator`。" #: ../../library/difflib.rst:531 msgid "" "Starting with the groups returned by :meth:`get_opcodes`, this method splits" " out smaller change clusters and eliminates intervening ranges which have no" " changes." msgstr "从 :meth:`get_opcodes` 所返回的组开始,此方法会拆分出较小的更改簇并消除没有更改的间隔区域。" #: ../../library/difflib.rst:535 msgid "The groups are returned in the same format as :meth:`get_opcodes`." msgstr "这些分组以与 :meth:`get_opcodes` 相同的格式返回。" #: ../../library/difflib.rst:540 msgid "" "Return a measure of the sequences' similarity as a float in the range [0, " "1]." msgstr "返回一个取值范围 [0, 1] 的浮点数作为序列相似性度量。" #: ../../library/difflib.rst:543 msgid "" "Where T is the total number of elements in both sequences, and M is the " "number of matches, this is 2.0\\*M / T. Note that this is ``1.0`` if the " "sequences are identical, and ``0.0`` if they have nothing in common." msgstr "" "其中 T 是两个序列中元素的总数量,M 是匹配的数量,即 2.0\\*M / T。 请注意如果两个序列完全相同则该值为 " "``1.0``,如果两者完全不同则为 ``0.0``。" #: ../../library/difflib.rst:547 msgid "" "This is expensive to compute if :meth:`get_matching_blocks` or " ":meth:`get_opcodes` hasn't already been called, in which case you may want " "to try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an upper" " bound." msgstr "" "如果 :meth:`get_matching_blocks` 或 :meth:`get_opcodes` " "尚未被调用则此方法运算消耗较大,在此情况下你可能需要先调用 :meth:`quick_ratio` 或 :meth:`real_quick_ratio`" " 来获取一个上界。" #: ../../library/difflib.rst:554 msgid "" "Caution: The result of a :meth:`ratio` call may depend on the order of the " "arguments. For instance::" msgstr "注意: :meth:`ratio` 调用的结果可能会取决于参数的顺序。 例如::" #: ../../library/difflib.rst:557 msgid "" ">>> SequenceMatcher(None, 'tide', 'diet').ratio()\n" "0.25\n" ">>> SequenceMatcher(None, 'diet', 'tide').ratio()\n" "0.5" msgstr "" ">>> SequenceMatcher(None, 'tide', 'diet').ratio()\n" "0.25\n" ">>> SequenceMatcher(None, 'diet', 'tide').ratio()\n" "0.5" #: ../../library/difflib.rst:565 msgid "Return an upper bound on :meth:`ratio` relatively quickly." msgstr "相对快速地返回一个 :meth:`ratio` 的上界。" #: ../../library/difflib.rst:570 msgid "Return an upper bound on :meth:`ratio` very quickly." msgstr "非常快速地返回一个 :meth:`ratio` 的上界。" #: ../../library/difflib.rst:573 msgid "" "The three methods that return the ratio of matching to total characters can " "give different results due to differing levels of approximation, although " ":meth:`~SequenceMatcher.quick_ratio` and " ":meth:`~SequenceMatcher.real_quick_ratio` are always at least as large as " ":meth:`~SequenceMatcher.ratio`:" msgstr "" "这三个返回匹配部分点总字符数之比的三种方法可能由于不同的近似级别而给出不同的结果,但是 " ":meth:`~SequenceMatcher.quick_ratio` 和 " ":meth:`~SequenceMatcher.real_quick_ratio` 总是会至少与 " ":meth:`~SequenceMatcher.ratio` 一样大:" #: ../../library/difflib.rst:590 msgid "SequenceMatcher Examples" msgstr "SequenceMatcher 的示例" #: ../../library/difflib.rst:592 msgid "This example compares two strings, considering blanks to be \"junk\":" msgstr "以下示例比较两个字符串,并将空格视为“垃圾”:" #: ../../library/difflib.rst:598 msgid "" ":meth:`~SequenceMatcher.ratio` returns a float in [0, 1], measuring the " "similarity of the sequences. As a rule of thumb, a " ":meth:`~SequenceMatcher.ratio` value over 0.6 means the sequences are close " "matches:" msgstr "" ":meth:`~SequenceMatcher.ratio` 返回一个 [0, 1] 范围内的浮点数,用来衡量序列的相似度。 " "根据经验,:meth:`~SequenceMatcher.ratio` 值超过 0.6 就意味着两个序列非常接近匹配:" #: ../../library/difflib.rst:605 msgid "" "If you're only interested in where the sequences match, " ":meth:`~SequenceMatcher.get_matching_blocks` is handy:" msgstr "如果您只对序列的匹配的位置感兴趣,则 :meth:`~SequenceMatcher.get_matching_blocks` 就很方便:" #: ../../library/difflib.rst:614 msgid "" "Note that the last tuple returned by " ":meth:`~SequenceMatcher.get_matching_blocks` is always a dummy, ``(len(a), " "len(b), 0)``, and this is the only case in which the last tuple element " "(number of elements matched) is ``0``." msgstr "" "请注意 :meth:`~SequenceMatcher.get_matching_blocks` 返回的最后一个元组 ``(len(a), " "len(b), 0)`` 始终只用于占位,这也是元组的末尾元素(匹配的元素个数)为 ``0`` 的唯一情况。" #: ../../library/difflib.rst:618 msgid "" "If you want to know how to change the first sequence into the second, use " ":meth:`~SequenceMatcher.get_opcodes`:" msgstr "如果你想要知道如何将第一个序列转成第二个序列,可以使用 :meth:`~SequenceMatcher.get_opcodes`:" #: ../../library/difflib.rst:629 msgid "" "The :func:`get_close_matches` function in this module which shows how simple" " code building on :class:`SequenceMatcher` can be used to do useful work." msgstr "" "此模块中的 :func:`get_close_matches` 函数显示了如何基于 :class:`SequenceMatcher` " "构建简单的代码来执行有用的功能。" #: ../../library/difflib.rst:633 msgid "" "`Simple version control recipe " "`_ for " "a small application built with :class:`SequenceMatcher`." msgstr "" "针对使用 :class:`SequenceMatcher` 构建的小型应用程序的 `简易版本控制方案 " "`_。" #: ../../library/difflib.rst:641 msgid "Differ Objects" msgstr "Differ 对象" #: ../../library/difflib.rst:643 msgid "" "Note that :class:`Differ`\\ -generated deltas make no claim to be " "**minimal** diffs. To the contrary, minimal diffs are often counter-" "intuitive, because they synch up anywhere possible, sometimes accidental " "matches 100 pages apart. Restricting synch points to contiguous matches " "preserves some notion of locality, at the occasional cost of producing a " "longer diff." msgstr "" "请注意 :class:`Differ` 所生成的增量并不保证是 **最小** 差异。 " "相反,最小差异往往是违反直觉的,因为它们会同步任何可能的地方,有时甚至意外产生相距 100 页的匹配。 " "将同步点限制为连续匹配保留了一些局部性概念,这偶尔会带来产生更长差异的代价。" #: ../../library/difflib.rst:649 msgid "The :class:`Differ` class has this constructor:" msgstr ":class:`Differ` 类具有这样的构造器:" #: ../../library/difflib.rst:655 msgid "" "Optional keyword parameters *linejunk* and *charjunk* are for filter " "functions (or ``None``):" msgstr "可选关键字形参 *linejunk* 和 *charjunk* 均为过滤函数 (或为 ``None``):" #: ../../library/difflib.rst:658 msgid "" "*linejunk*: A function that accepts a single string argument, and returns " "true if the string is junk. The default is ``None``, meaning that no line " "is considered junk." msgstr "" "*linejunk*: 接受单个字符串作为参数的函数,如果其为垃圾字符串则返回真值。 默认值为 ``None``,意味着没有任何行会被视为垃圾行。" #: ../../library/difflib.rst:662 msgid "" "*charjunk*: A function that accepts a single character argument (a string of" " length 1), and returns true if the character is junk. The default is " "``None``, meaning that no character is considered junk." msgstr "" "*charjunk*: 接受单个字符(长度为 1 的字符串)作为参数的函数,如果其为垃圾字符则返回真值。 默认值为 " "``None``,意味着没有任何字符会被视为垃圾字符。" #: ../../library/difflib.rst:666 msgid "" "These junk-filtering functions speed up matching to find differences and do " "not cause any differing lines or characters to be ignored. Read the " "description of the :meth:`~SequenceMatcher.find_longest_match` method's " "*isjunk* parameter for an explanation." msgstr "" "这些垃圾过滤函数可加快查找差异的匹配速度,并且不会导致任何差异行或字符被忽略。 请阅读 " ":meth:`~SequenceMatcher.find_longest_match` 方法的 *isjunk* 形参的描述了解详情。" #: ../../library/difflib.rst:672 msgid "" ":class:`Differ` objects are used (deltas generated) via a single method:" msgstr ":class:`Differ` 对象是通过一个单独方法来使用(生成增量)的:" #: ../../library/difflib.rst:677 msgid "" "Compare two sequences of lines, and generate the delta (a sequence of " "lines)." msgstr "比较两个由行组成的序列,并生成增量(一个由行组成的序列)。" #: ../../library/difflib.rst:679 msgid "" "Each sequence must contain individual single-line strings ending with " "newlines. Such sequences can be obtained from the " ":meth:`~io.IOBase.readlines` method of file-like objects. The delta " "generated also consists of newline-terminated strings, ready to be printed " "as-is via the :meth:`~io.IOBase.writelines` method of a file-like object." msgstr "" "每个序列必须包含一个以换行符结尾的单行字符串。 这样的序列可以通过文件型对象的 :meth:`~io.IOBase.readlines` 方法来获取。 " "所生成的增量同样由以换行符结尾的字符串构成,可以通过文件型对象的 :meth:`~io.IOBase.writelines` 方法原样打印出来。" #: ../../library/difflib.rst:690 msgid "Differ Example" msgstr "Differ 示例" #: ../../library/difflib.rst:692 msgid "" "This example compares two texts. First we set up the texts, sequences of " "individual single-line strings ending with newlines (such sequences can also" " be obtained from the :meth:`~io.IOBase.readlines` method of file-like " "objects):" msgstr "" "此示例比较两段文本。 首先我们设置文本为以换行符结尾的单行字符串组成的序列(这样的序列也可以通过文件型对象的 " ":meth:`~io.IOBase.readlines` 方法来获取):" #: ../../library/difflib.rst:711 msgid "Next we instantiate a Differ object:" msgstr "接下来我们实例化一个 Differ 对象:" #: ../../library/difflib.rst:715 msgid "" "Note that when instantiating a :class:`Differ` object we may pass functions " "to filter out line and character \"junk.\" See the :meth:`Differ` " "constructor for details." msgstr "" "请注意在实例化 :class:`Differ` 对象时我们可以传入函数来过滤掉“垃圾”行和字符。 详情参见 :meth:`Differ` 构造器说明。" #: ../../library/difflib.rst:719 msgid "Finally, we compare the two:" msgstr "最后,我们比较两个序列:" #: ../../library/difflib.rst:723 msgid "``result`` is a list of strings, so let's pretty-print it:" msgstr "``result`` 是一个字符串列表,让我们将其美化打印出来:" #: ../../library/difflib.rst:738 msgid "As a single multi-line string it looks like this:" msgstr "作为单独的多行字符串显示出来则是这样:" #: ../../library/difflib.rst:757 msgid "A command-line interface to difflib" msgstr "difflib 的命令行接口" #: ../../library/difflib.rst:759 msgid "" "This example shows how to use difflib to create a ``diff``-like utility." msgstr "这个例子演示了如何使用 difflib 来创建类似 ``diff`` 的工具。" #: ../../library/difflib.rst:761 msgid "" "\"\"\" Command line interface to difflib.py providing diffs in four formats:\n" "\n" "* ndiff: lists every line and highlights interline changes.\n" "* context: highlights clusters of changes in a before/after format.\n" "* unified: highlights clusters of changes in an inline format.\n" "* html: generates side by side comparison with change highlights.\n" "\n" "\"\"\"\n" "\n" "import sys, os, difflib, argparse\n" "from datetime import datetime, timezone\n" "\n" "def file_mtime(path):\n" " t = datetime.fromtimestamp(os.stat(path).st_mtime,\n" " timezone.utc)\n" " return t.astimezone().isoformat()\n" "\n" "def main():\n" "\n" " parser = argparse.ArgumentParser()\n" " parser.add_argument('-c', action='store_true', default=False,\n" " help='Produce a context format diff (default)')\n" " parser.add_argument('-u', action='store_true', default=False,\n" " help='Produce a unified format diff')\n" " parser.add_argument('-m', action='store_true', default=False,\n" " help='Produce HTML side by side diff '\n" " '(can use -c and -l in conjunction)')\n" " parser.add_argument('-n', action='store_true', default=False,\n" " help='Produce a ndiff format diff')\n" " parser.add_argument('-l', '--lines', type=int, default=3,\n" " help='Set number of context lines (default 3)')\n" " parser.add_argument('fromfile')\n" " parser.add_argument('tofile')\n" " options = parser.parse_args()\n" "\n" " n = options.lines\n" " fromfile = options.fromfile\n" " tofile = options.tofile\n" "\n" " fromdate = file_mtime(fromfile)\n" " todate = file_mtime(tofile)\n" " with open(fromfile) as ff:\n" " fromlines = ff.readlines()\n" " with open(tofile) as tf:\n" " tolines = tf.readlines()\n" "\n" " if options.u:\n" " diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)\n" " elif options.n:\n" " diff = difflib.ndiff(fromlines, tolines)\n" " elif options.m:\n" " diff = difflib.HtmlDiff().make_file(fromlines,tolines,fromfile,tofile,context=options.c,numlines=n)\n" " else:\n" " diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)\n" "\n" " sys.stdout.writelines(diff)\n" "\n" "if __name__ == '__main__':\n" " main()\n" msgstr "" "\"\"\" difflib.py 的命令行接口,提供四种格式的 diff:\n" "\n" "* ndiff: 列出每一行并高亮各行间的变化。\n" "* context: 以前/后格式高亮变化内容集。\n" "* unified: 以内联格式高亮变化内容集。\n" "* html: 生成高亮变化内容的并排比较。\n" "\n" "\"\"\"\n" "\n" "import sys, os, difflib, argparse\n" "from datetime import datetime, timezone\n" "\n" "def file_mtime(path):\n" " t = datetime.fromtimestamp(os.stat(path).st_mtime,\n" " timezone.utc)\n" " return t.astimezone().isoformat()\n" "\n" "def main():\n" "\n" " parser = argparse.ArgumentParser()\n" " parser.add_argument('-c', action='store_true', default=False,\n" " help='Produce a context format diff (default)')\n" " parser.add_argument('-u', action='store_true', default=False,\n" " help='Produce a unified format diff')\n" " parser.add_argument('-m', action='store_true', default=False,\n" " help='Produce HTML side by side diff '\n" " '(can use -c and -l in conjunction)')\n" " parser.add_argument('-n', action='store_true', default=False,\n" " help='Produce a ndiff format diff')\n" " parser.add_argument('-l', '--lines', type=int, default=3,\n" " help='Set number of context lines (default 3)')\n" " parser.add_argument('fromfile')\n" " parser.add_argument('tofile')\n" " options = parser.parse_args()\n" "\n" " n = options.lines\n" " fromfile = options.fromfile\n" " tofile = options.tofile\n" "\n" " fromdate = file_mtime(fromfile)\n" " todate = file_mtime(tofile)\n" " with open(fromfile) as ff:\n" " fromlines = ff.readlines()\n" " with open(tofile) as tf:\n" " tolines = tf.readlines()\n" "\n" " if options.u:\n" " diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)\n" " elif options.n:\n" " diff = difflib.ndiff(fromlines, tolines)\n" " elif options.m:\n" " diff = difflib.HtmlDiff().make_file(fromlines,tolines,fromfile,tofile,context=options.c,numlines=n)\n" " else:\n" " diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)\n" "\n" " sys.stdout.writelines(diff)\n" "\n" "if __name__ == '__main__':\n" " main()\n" #: ../../library/difflib.rst:764 msgid "ndiff example" msgstr "ndiff 示例" #: ../../library/difflib.rst:766 msgid "This example shows how to use :func:`difflib.ndiff`." msgstr "这个例子演示了如何使用 :func:`difflib.ndiff`。" #: ../../library/difflib.rst:768 msgid "" "\"\"\"ndiff [-q] file1 file2\n" " or\n" "ndiff (-r1 | -r2) < ndiff_output > file1_or_file2\n" "\n" "Print a human-friendly file difference report to stdout. Both inter-\n" "and intra-line differences are noted. In the second form, recreate file1\n" "(-r1) or file2 (-r2) on stdout, from an ndiff report on stdin.\n" "\n" "In the first form, if -q (\"quiet\") is not specified, the first two lines\n" "of output are\n" "\n" "-: file1\n" "+: file2\n" "\n" "Each remaining line begins with a two-letter code:\n" "\n" " \"- \" line unique to file1\n" " \"+ \" line unique to file2\n" " \" \" line common to both files\n" " \"? \" line not present in either input file\n" "\n" "Lines beginning with \"? \" attempt to guide the eye to intraline\n" "differences, and were not present in either input file. These lines can be\n" "confusing if the source files contain tab characters.\n" "\n" "The first file can be recovered by retaining only lines that begin with\n" "\" \" or \"- \", and deleting those 2-character prefixes; use ndiff with -r1.\n" "\n" "The second file can be recovered similarly, but by retaining only \" \" and\n" "\"+ \" lines; use ndiff with -r2; or, on Unix, the second file can be\n" "recovered by piping the output through\n" "\n" " sed -n '/^[+ ] /s/^..//p'\n" "\"\"\"\n" "\n" "__version__ = 1, 7, 0\n" "\n" "import difflib, sys\n" "\n" "def fail(msg):\n" " out = sys.stderr.write\n" " out(msg + \"\\n\\n\")\n" " out(__doc__)\n" " return 0\n" "\n" "# open a file & return the file object; gripe and return 0 if it\n" "# couldn't be opened\n" "def fopen(fname):\n" " try:\n" " return open(fname)\n" " except IOError as detail:\n" " return fail(\"couldn't open \" + fname + \": \" + str(detail))\n" "\n" "# open two files & spray the diff to stdout; return false iff a problem\n" "def fcompare(f1name, f2name):\n" " f1 = fopen(f1name)\n" " f2 = fopen(f2name)\n" " if not f1 or not f2:\n" " return 0\n" "\n" " a = f1.readlines(); f1.close()\n" " b = f2.readlines(); f2.close()\n" " for line in difflib.ndiff(a, b):\n" " print(line, end=' ')\n" "\n" " return 1\n" "\n" "# crack args (sys.argv[1:] is normal) & compare;\n" "# return false iff a problem\n" "\n" "def main(args):\n" " import getopt\n" " try:\n" " opts, args = getopt.getopt(args, \"qr:\")\n" " except getopt.error as detail:\n" " return fail(str(detail))\n" " noisy = 1\n" " qseen = rseen = 0\n" " for opt, val in opts:\n" " if opt == \"-q\":\n" " qseen = 1\n" " noisy = 0\n" " elif opt == \"-r\":\n" " rseen = 1\n" " whichfile = val\n" " if qseen and rseen:\n" " return fail(\"can't specify both -q and -r\")\n" " if rseen:\n" " if args:\n" " return fail(\"no args allowed with -r option\")\n" " if whichfile in (\"1\", \"2\"):\n" " restore(whichfile)\n" " return 1\n" " return fail(\"-r value must be 1 or 2\")\n" " if len(args) != 2:\n" " return fail(\"need 2 filename args\")\n" " f1name, f2name = args\n" " if noisy:\n" " print('-:', f1name)\n" " print('+:', f2name)\n" " return fcompare(f1name, f2name)\n" "\n" "# read ndiff output from stdin, and print file1 (which=='1') or\n" "# file2 (which=='2') to stdout\n" "\n" "def restore(which):\n" " restored = difflib.restore(sys.stdin.readlines(), which)\n" " sys.stdout.writelines(restored)\n" "\n" "if __name__ == '__main__':\n" " main(sys.argv[1:])\n" msgstr "" "\"\"\"ndiff [-q] file1 file2\n" " 或\n" "ndiff (-r1 | -r2) < ndiff_output > file1_or_file2\n" "\n" "打印对人类友好的文件差异报告至标准输出。 将会标明\n" "行间与行内差异。 在第二种形式下,会根据标准输入上的\n" "ndiff 报告在标准输出上重建 file1 (-r1) 或 file2 (-r2)。\n" "\n" "在第一种形式下,如果未指明 -q (\"quiet\"),则输出的\n" "前两行为\n" "\n" "-: file1\n" "+: file2\n" "\n" "其余的每一行将以两个字符的代码打头:\n" "\n" " \"- \" 行不同于 file1\n" " \"+ \" 行不同于 file2\n" " \" \" 行在两个文件中相同\n" " \"? \" 行不存在于某一个输入文件\n" "\n" "以 \"? \" 打头的行会尝试关注行内差异,并且\n" "不存在于某一个输入文件中。 当源文件包含\n" "制表符时这些行可能会令人迷惑。\n" "\n" "第一个文件可通过只保留以\" \" 或 \"- \" 打头的行,\n" "并删除那些 2 字符前缀来恢复;使用 ndiff 时传入 -r1。\n" "\n" "第二个文件可通过类似方式来恢复,即只保留\n" "\" \" 和 \"+ \" 打头的行;使用 ndiff 并传入 -r2;或者\n" "在 Unix 上,第二个文件可通过管道操作来恢复\n" "\n" " sed -n '/^[+ ] /s/^..//p'\n" "\"\"\"\n" "\n" "__version__ = 1, 7, 0\n" "\n" "import difflib, sys\n" "\n" "def fail(msg):\n" " out = sys.stderr.write\n" " out(msg + \"\\n\\n\")\n" " out(__doc__)\n" " return 0\n" "\n" "# 打开一个文件并返回文件对象;如无法打开文件\n" "# 则返回 0\n" "def fopen(fname):\n" " try:\n" " return open(fname)\n" " except IOError as detail:\n" " return fail(\"couldn't open \" + fname + \": \" + str(detail))\n" "\n" "# 打开两个文件并报告差异至标准输出;如有问题则返回假值\n" "def fcompare(f1name, f2name):\n" " f1 = fopen(f1name)\n" " f2 = fopen(f2name)\n" " if not f1 or not f2:\n" " return 0\n" "\n" " a = f1.readlines(); f1.close()\n" " b = f2.readlines(); f2.close()\n" " for line in difflib.ndiff(a, b):\n" " print(line, end=' ')\n" "\n" " return 1\n" "\n" "# 解析参数 (sys.argv[1:] 正常) 并进行比较;\n" "# 如有问题则返回假值\n" "\n" "def main(args):\n" " import getopt\n" " try:\n" " opts, args = getopt.getopt(args, \"qr:\")\n" " except getopt.error as detail:\n" " return fail(str(detail))\n" " noisy = 1\n" " qseen = rseen = 0\n" " for opt, val in opts:\n" " if opt == \"-q\":\n" " qseen = 1\n" " noisy = 0\n" " elif opt == \"-r\":\n" " rseen = 1\n" " whichfile = val\n" " if qseen and rseen:\n" " return fail(\"can't specify both -q and -r\")\n" " if rseen:\n" " if args:\n" " return fail(\"no args allowed with -r option\")\n" " if whichfile in (\"1\", \"2\"):\n" " restore(whichfile)\n" " return 1\n" " return fail(\"-r value must be 1 or 2\")\n" " if len(args) != 2:\n" " return fail(\"need 2 filename args\")\n" " f1name, f2name = args\n" " if noisy:\n" " print('-:', f1name)\n" " print('+:', f2name)\n" " return fcompare(f1name, f2name)\n" "\n" "# 从标准输入读取 ndiff 输出,并打印 file1 (which=='1') 或\n" "# file2 (which=='2') 到标准输出\n" "\n" "def restore(which):\n" " restored = difflib.restore(sys.stdin.readlines(), which)\n" " sys.stdout.writelines(restored)\n" "\n" "if __name__ == '__main__':\n" " main(sys.argv[1:])\n"