我想從我的數據中提取一些信息。
正則表達式將不同的字符串拆分爲groupdict
最全行也許像下面(每個零件可能包含CJK字符):
0. (event) (tag) [group (artist)] title (form) [addition1] [addition2]
一行還可能有:
1. (event) [group (artist)] title (form) [addition1]
2. [event] [group (artist)] title (form) (addition1)
3. (tag) [group (artist)] title
4. [group (artist)] title
5. title
6. and something like above, such as 【tag】 [group (artist)] title 【form】
正如我們看到的,最簡單的行只是純文本title
, 我寫了一個正則表達式嘗試匹配所有這些文件
import re
regex_patern = ur'([\(\[](?P<event>[^\)\]]*)[\)\]])?\s*([\(\[](?P<type>[^\)\](\)\])]*)[\)\]])?\s*(\[(?P<group>[^\(\]]*)(\((?P<artist>[^\)]*)\))?\])?(?P<title>[^\(\)\[\]]*)([\(\[](?P<from>[^\)\]]*)[\)\]])?(\s*[\(\[](?P<more1>[^\)\]]*)[\)\]])'
p = re.compile(regex_patern)
rows= [
'(event) (tag) [group (artist)] title (form) [addition1] [addition2]',
'(event) [group (artist)] title (form) [addition1]',
'[event] [group (artist)] title (form) (addition1)',
'(tag) [group (artist)] title',
'[group (artist)] title',
'title',
]
for r in rows:
r = re.search(p, r)
print r.groupdict()
輸出:
{u'from': 'form', u'more1': 'addition1', u'artist': 'artist', u'title': ' title ', u'group': 'group ', u'type': 'tag', u'event': 'event'}
{u'from': 'form', u'more1': 'addition1', u'artist': 'artist', u'title': ' title ', u'group': 'group ', u'type': None, u'event': 'event'}
{u'from': 'form', u'more1': 'addition1', u'artist': 'artist', u'title': ' title ', u'group': 'group ', u'type': None, u'event': 'event'}
{u'from': None, u'more1': 'group (artist', u'artist': None, u'title': '', u'group': None, u'type': None, u'event': 'tag'}
{u'from': None, u'more1': 'group (artist', u'artist': None, u'title': '', u'group': None, u'type': None, u'event': None}
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-5-831c548bc3f0> in <module>()
15 for r in rows:
16 r = re.search(p, r)
---> 17 print r.groupdict()
AttributeError: 'NoneType' object has no attribute 'groupdict'
結果成爲意外從第4行
我認爲re
應該從中間搜索。首先尋找[group (artist)] and title
,但我不知道如何寫在正則表達式。 或者我正在做錯誤的方式?
'title'與正則表達式不匹配,因此您有問題。我猜'如果r: \t print r.groupdict()'不是你想要的,對嗎 –
@stribizhev我想正確地得到所有屬性。第4行:u'more1':'group(artist',u'artist',this attribute was wrong。 – Mithril
I updated answer –