4

重複の可能性:
Python: 複数の区切り文字で文字列を分割

Pythonで同様のことを行うことはできますか?

VB.net の分割方法:

Dim line As String = "Tech ID: xxxxxxxxxx Name: DOE, JOHN Account #: xxxxxxxx"
Dim separators() As String = {"Tech ID:", "Name:", "Account #:"}
Dim result() As String
result = line.Split(separators, StringSplitOptions.RemoveEmptyEntries)
4

3 に答える 3

2

このような不適切なデータ形式が与えられた場合、次のことを試すことができますre.split()

>>> import re
>>> mystring = "Field 1: Data 1 Field 2: Data 2 Field 3: Data 3"
>>> a = re.split(r"(Field 1:|Field 2:|Field 3:)",mystring)
['', 'Field 1:', ' Data 1 ', 'Field 2:', ' Data 2 ', 'Field 3:', ' Data 3']

引用符で囲まれた文字列とカンマ区切りのレコードを使用して、データが適切にフォーマットされていれば、作業ははるかに簡単になります。これによりcsv、コンマ区切り値ファイルの解析にモジュールを使用できるようになります。

編集:

リスト内包表記を使用して空白のエントリを除外できます。

>>> a_non_empty = [s for s in a if s]
>>> a_non_empty
['Field 1:', ' Data 1 ', 'Field 2:', ' Data 2 ', 'Field 3:', ' Data 3']
于 2012-05-03T06:03:50.747 に答える
1
>>> import re
>>> str = "Tech ID: xxxxxxxxxx Name: DOE, JOHN Account #: xxxxxxxx"
>>> re.split("Tech ID:|Name:|Account #:",str)
['', ' xxxxxxxxxx ', ' DOE, JOHN ', ' xxxxxxxx']
于 2012-05-03T06:05:10.417 に答える
0

別のアプローチをお勧めします。

>>> import re
>>> subject = "Tech ID: xxxxxxxxxx Name: DOE, JOHN Account #: xxxxxxxx"
>>> regex = re.compile(r"(Tech ID|Name|Account #):\s*(.*?)\s*(?=Tech ID:|Name:|Account #:|$)")
>>> dict(regex.findall(subject))
{'Tech ID': 'xxxxxxxxxx', 'Name': 'DOE, JOHN', 'Account #': 'xxxxxxxx'}

そうすれば、この種のデータに役立つデータ構造である辞書を取得できます。

コメント付きの正規表現として:

regex = re.compile(
    r"""(?x)                         # Verbose regex:
    (Tech\ ID|Name|Account\ \#)      # Match identifier
    :                                # Match a colon
    \s*                              # Match optional whitespace
    (.*?)                            # Match any number of characters, as few as possible
    \s*                              # Match optional whitespace
    (?=                              # Assert that the following can be matched:
     Tech\ ID:|Name:|Account\ \#:    # The next identifier
     |$                              # or the end of the string
    )                                # End of lookahead assertion""")
于 2012-05-03T06:32:59.480 に答える