2

test.txt には、2 行の文があります。

The heart was made to be broken.
There is no surprise more magical than the surprise of being loved.

コード:

import re
file = open('/test.txt','r')#specify file to open
data = file.readlines()
file.close()
for line in data:
    line_split = re.split(r'[ \t\n\r, ]+',line)
    print line_split

コードの結果:

['The', 'heart', 'was', 'made', 'to', 'be', 'broken.', '']
['There', 'is', 'no', 'surprise', 'more', 'magical', 'than', 'the', 'surprise', 'of', 'being', 'loved.']

Wordのみを印刷するには?(最初の文を参照) 期待される結果:

['The', 'heart', 'was', 'made', 'to', 'be', 'broken.']
['There', 'is', 'no', 'surprise', 'more', 'magical', 'than', 'the', 'surprise', 'of', 'being', 'loved.']

何かアドバイス?

4

4 に答える 4

3

splitを使用して区切り文字を一致させる代わりにfindall、否定された正規表現を使用して、保持したい部分を一致させることができます。

line_split = re.findall(r'[^ \t\n\r., ]+',line)

オンラインでの動作を確認してください: ideone

于 2012-05-05T20:58:01.167 に答える
1
words = re.compile(r"[\w']+").findall(yourString)

デモ

>>> yourString = "Mary's lamb was white as snow."
["Mary's", 'lamb', 'was', 'white', 'as', 'snow']

本当に期間が必要な場合は、次のように追加できます[\w'\.]

于 2012-05-05T21:38:31.890 に答える
1

修正するには、他のいくつかの変更を加えて、さらに説明します。

import re

with open("test.txt", "r") as file:
    for line in file:
        line_split = filter(bool, re.split(r'[ \t\n\r, ]+', line))
        print(line_split)

ここではfilter()、結果から空の文字列を削除するために a を使用します。

ファイルを開くためwithステートメントの使用に注意してください。これは読みやすく、例外が発生した場合でもファイルを閉じる処理を行います。

また、ファイルを直接ループします。これは、ファイル全体を一度にメモリにロードしないため、より良いアイデアです。これは不要であり、大きなファイルで問題が発生する可能性があります。

于 2012-05-05T20:59:38.300 に答える
0
In [2]: with open('test.txt','r') as f:
   ...:     lines = f.readlines()
   ...:

In [3]: words = [l.split() for l in lines]

In [4]: words
Out[4]:
[['The', 'heart', 'was', 'made', 'to', 'be', 'broken.'],
 ['There',
  'is',
  'no',
  'surprise',
  'more',
  'magical',
  'than',
  'the',
  'surprise',
  'of',
  'being',
  'loved.']]
于 2012-05-06T04:50:43.370 に答える