脚本は、一気に読み込めるように短くする必要があります。その場合は、translate
メソッドを使用してすべての句読点を削除できます。最後に、次を使用して空白で分割するだけで、リストを作成できますstr.split
。
import string
with open('screenplay.txt', 'rb') as f:
content = f.read()
content = content.translate(None, string.punctuation).lower()
words = content.split()
print words
Mr.Smith
に変わりますのでご注意くださいmrsmith
。になりたい場合['mr', 'smith']
は、すべての句読点をスペースに置き換えてから、次を使用できますstr.split
。
def using_translate(content):
table = string.maketrans(
string.punctuation,
' '*len(string.punctuation))
content = content.translate(table).lower()
words = content.split()
return words
などの正の正規表現パターンを使用して発生する可能性のある問題の 1 つ[a-z]+
は、ASCII 文字のみに一致することです。ファイルにアクセント付きの文字が含まれていると、単語が分割されます。
Gruyère
となり['Gruy','re']
ます。
re.split
句読点で分割するために使用することで修正できます。例えば、
def using_re(content):
words = re.split(r"[ %s\t\n]+" % (string.punctuation,), content.lower())
return words
ただし、使用するstr.translate
方が高速です。
In [72]: %timeit using_re(content)
100000 loops, best of 3: 9.97 us per loop
In [73]: %timeit using_translate(content)
100000 loops, best of 3: 3.05 us per loop