3

私はPythonの初心者であり、Pythonがテキストファイルから引用符で囲まれたすべてのテキストをキャプチャすることを望んでいます。私は以下を試しました:

filename = raw_input("Enter the full path of the file to be used: ")
input = open(filename, 'r')
import re
quotes = re.findall(ur'"[\^u201d]*["\u201d]', input)
print quotes

エラーが発生します:

Traceback (most recent call last):
  File "/Users/nithin/Documents/Python/Capture Quotes", line 5, in <module>
    quotes = re.findall(ur'"[\^u201d]*["\u201d]', input)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 177, in findall
    return _compile(pattern, flags).findall(string)
TypeError: expected string or buffer

誰かが私を助けることができますか?

4

2 に答える 2

2

Bakuriu が指摘したように、次.read()のように追加する必要があります。

quotes = re.findall(ur'[^\u201d]*[\u201d]', input.read())

open()は単にファイル オブジェクトを返しますが、f.read()は文字列を返します。さらに、引用符の前に0回以上出現するのではなく、2つの引用符の間のすべてを取得しようとしていると思います[\^u201d]。だから私はこれを試してみます:

quotes = re.findall(ur'[\u201d][^\u201d]*[\u201d]', input.read(), re.U)

ユニコードのre.Uアカウント。または (2 組の右二重引用符がなく、Unicode が必要ない場合):

quotes = re.findall(r'"[^"]*"', input.read(), re.U)

最後に、は Python のキーワードであるinputため、以外の変数を選択することもできます。input

結果は次のようになります。

>>> input2 = """
cfrhubecf "ehukl wehunkl echnk
wehukb ewni; wejio;"
"werulih"
"""
>>> quotes = re.findall(r'"[^"]*"', input2, re.U)
>>> print quotes
['"ehukl wehunkl echnk\nwehukb ewni; wejio;"', '"werulih"']
于 2013-01-30T19:51:31.640 に答える
0

正規表現を使用する代わりに、いくつかのPythonビルトインを試すことができます。あなたに大変な仕事をさせましょう:

message = '''
"some text in quotes", some text not in quotes. Some more text 'In different kinds of quotes'.
'''
list_of_single_quote_items = message.split("'")
list_of_double_quote_items = message.split(""")

難しい部分は、分割リストの意味を解釈し、すべてのエッジ条件(文字列内の1つの引用符、エスケープシーケンスなど)を処理することです。

于 2013-01-30T19:47:31.043 に答える