0

このような

text = "  \t  hello there\n  \t  how are you?\n  \t HHHH"
      hello there
      how are you?
     HHHH

正規表現を介して共通のプレフィックス部分文字列を取得できますか?

試みる

In [36]: re.findall(r"(?m)(?:(^[ \t]+).+[\n\r]+\1)", "  \t  hello there\n  \t  how are you?\n  \t HHHH")
Out[36]: ['  \t  ']

しかし、どうやらその一般的なプレフィックス部分文字列は ' \t 'であり、python textwrap モジュールのような関数
に使用したいと考えています。dedent

4

4 に答える 4

1

私は提案します

match = re.search(r'(?m)\A(.*).*(?:\n?^\1.*$)*\n?\Z', text)

このデモを参照してください。

于 2012-11-03T13:25:38.110 に答える
1

テキスト内の一般的な接頭辞を見つける式は次のとおりです。

r'^(.+).*(\n\1.*)*$'

例:

import re

text = (
    "No Red Leicester\n"
    "No Tilsit\n"
    "No Red Windsor"
)

m = re.match(r'^(.+).*(\n\1.*)*$', text)
if m:
    print 'common prefix is', m.group(1)
else:
    print 'no common prefix'

この式には多くのバックトラックが含まれるため、特に大きな入力では慎重に使用してください。

最も長い一般的な「スペース」プレフィックスを見つけるには、それらをすべて見つけて適用しますlen

def dedent(text):
    prefix_len = min(map(len, re.findall('(?m)^\s+', text)))
    return re.sub(r'(?m)^.{%d}' % prefix_len, '', text)

text = (
    "     No Red Leicester\n"
    "    No Tilsit\n"
    "\t\t   No Red Windsor"
)

print dedent(text)
于 2012-11-03T10:40:29.720 に答える
0

私は Python があまり得意ではないので、このコードはこの言語の慣用句ではないように見えるかもしれませんが、アルゴリズム的には適切なはずです。

>>> import StringIO
...
>>> def strip_common_prefix(text):
...     position = text.find('\n')
...     offset = position
...     match = text[: position + 1]
...     lines = [match]
...     while match and position != len(text):
...         next_line = text.find('\n', position + 1)
...         if next_line == -1: next_line = len(text)
...         line = text[position + 1 : next_line + 1]
...         position = next_line
...         lines.append(line)
...         i = 0
...         for a, b in zip(line, match):
...             if i > offset or a != b: break
...             i += 1
...         offset = i
...         match = line[: offset]
...     buf = StringIO.StringIO()
...     for line in lines:
...         if not match: buf.write(line)
...         else: buf.write(line[offset :])
...     text = buf.getvalue()
...     buf.close()
...     return text
... 
>>> strip_common_prefix("  \t  hello there\n  \t  how are you?\n  \t HHHH")
' hello there\n how are you?\nHHHH'
>>> 

正規表現には、これに加えて多くのオーバーヘッドがあります。

于 2012-11-03T13:28:39.897 に答える