tcl string map
に最も近いのはstr.translateですが、残念ながら1文字しかマッピングできません。したがって、コンパクトな例を得るためには正規表現を使用する必要があります。これはlook-behind/look-ahead assertionsで行うことができますが、\r
年代は、最初に交換することがあります。
import re
oldtext = """\
This would keep paragraphs separated.
This would keep paragraphs separated.
This would keep paragraphs separated.
\tThis would keep paragraphs separated.
\rWhen, in the course
of human events,
it becomes necessary
\rfor one people
"""
newtext = re.sub(r'(?<!\n)\n(?![\n\t])', ' ', oldtext.replace('\r', ''))
出力:
This would keep paragraphs separated. This would keep paragraphs separated.
This would keep paragraphs separated.
This would keep paragraphs separated.
When, in the course of human events, it becomes necessary for one people
私はこれはしかし、TCLコードほど効率的であるかどうかを疑います。
UPDATE:
私はこのProject Gutenberg EBook of War and Peace(プレーンテキストUTF-8、3.1メガバイト)を使用して、少しテストをしました。
set fp [open "gutenberg.txt" r]
set oldtext [read $fp]
close $fp
set newtext [string map "{\r} {} {\n\n} {\n\n} {\n\t} {\n\t} {\n} { }" $oldtext]
puts $newtext
と私のpythonと同等:
import re
with open('gutenberg.txt') as stream:
oldtext = stream.read()
newtext = re.sub(r'(?<!\n)\n(?![\n\t])', ' ', oldtext.replace('\r', ''))
print(newtext)
原油性能試験:
$ /usr/bin/time -f '%E' tclsh gutenberg.tcl > output1.txt
0:00.18
$ /usr/bin/time -f '%E' python gutenberg.py > output2.txt
0:00.30
ので、予想通り、TCLバージョンは、より効率的であるここに私のTCLスクリプトです。しかし、Pythonのバージョンからの出力はややクリーナーです(行頭に余分なスペースは挿入されません)。 「人間イベントNOFコース\には、\ nは1人Nforの\必要になった場合、」 >>> whenin = >>> 再インポート>>>:
いくつかの改行を処分した
あなたのコードには末尾に余分な括弧が付いています。これは構文エラーですが、余分な括弧を削除してもうまくいきました。また、 '\ r'と' \ n'を取り除く必要があることを思い出しました。私はこれをProject Gutenbergの巨大なテキストファイルを使ってTclコードと比較して時間テストを実行するために、他の人に任せておきます。 :o) – McClamrock
私はちょうど思い出しました。 。 。私は '\ r'も覚えていましたが、そうでした。 – McClamrock
@McClamrock。私のサンプルコードを修正しました:ありがとう。私はいくつかのタイミングを取ってもいいかもしれませんが、最初に少しtclを学ぶ必要があります;-) – ekhumoro