我有跟随线。
DATE: 12242010Key Type: Nod32 Anti-Vir (30d trial) Key: a5B2s-sH12B-hgtY3-io87N-srg98-KLMNO我需要创建字典,这样它就像
{
"DATE": "12242010",
"Key Type": "Nod32 Anti-Vir (30d trial)",
"Key": "a5B2s-sH12B-hgtY3-io87N-srg98-KLMNO"
}问题是字符串未格式化。
DATE: 12242010Key Type: Nod32 Anti-Vir (30d trial) ,最好对密钥进行一些验证。
我是python的初学者,而且是正则表达式的初学者。非常感谢。
这是我的密码。我正在从xpath获得字符串。为什么我不能用在regex里?
import re
import lxml.html as my_lxml_hmtl
tree = my_lxml_hmtl.parse("test.html")
text = tree.xpath("string(//*[contains(text(),'DATE')])")
# this works
print re.match('DATE:\s+([0-9]{8})\s*Key Type:\s+(.+)\s+Key:\s+((?:[^-]{5}(?:-[^-]{5})*))', 'DATE: 12242010Key Type: Nod32 Anti-Vir (30d trial) Key: a5B2s-sH12B-hgtY3-io87N-srg98-KLMNO').groups()
# and this doesn't work, why?
ss = str(text)
# print ss gives the same string which worked in re fabove
print re.match('DATE:\s+([0-9]{8})\s*Key Type:\s+(.+)\s+Key:\s+((?:[^-]{5}(?:-[^-]{5})*))', ss).groups()当我试图使用文本或str(文本)代替‘日期:12242010键类型: Nod32反Vir (30d试用)键:a5B2s-sH12B-hgtY3-io87N-srg98 98-KLMNO’,我得到一个错误AttributeError:'NoneType‘对象没有属性’组‘。
这里怎么了?
发布于 2010-12-24 10:23:48
>>> import re
>>> regex = re.compile(r"DATE: (\d+)Key Type: (.*?) Key: ((?:\w{5}-){5}\w{5})")
>>> match = regex.match("DATE: 12242010Key Type: Nod32 Anti-Vir (30d trial) Key: a5B2s-sH12B-hgtY3-io87N-srg98-KLMNO")
>>> mydict = {"DATE": match.group(1),
... "Key Type": match.group(2),
... "Key": match.group(3)}
>>> mydict
{'DATE': '12242010', 'Key': 'a5B2s-sH12B-hgtY3-io87N-srg98-KLMNO', 'Key Type': '
Nod32 Anti-Vir (30d trial)'}
>>>regex DATE: (\d+)Key Type: (.*?) Key: ((?:\w{5}-){5}\w{5})匹配日期(仅为数字)和键类型(任何字符);然后它匹配一个键,如果它由六个组组成,每个组由五个字母数字字符组成,用破折号分隔。
发布于 2010-12-24 10:23:51
如果您可以依赖于标题是相同的,那么您就幸运了。
>>> re.match('DATE:\s+([0-9]{8})\s*Key Type:\s+(.+)\s+Key:\s+((?:[^-]{5}(?:-[^-]{5})*))', 'DATE: 12242010Key Type: Nod32 Anti-Vir (30d trial) Key: a5B2s-sH12B-hgtY3-io87N-srg98-KLMNO').groups()
('12242010', 'Nod32 Anti-Vir (30d trial)', 'a5B2s-sH12B-hgtY3-io87N-srg98-KLMNO')但是,如果您期望组数发生变化,则可能需要在后处理中得到组数。
发布于 2010-12-24 20:45:36
import re
def strToDict(inStr, keyList, sep=''):
rxPieces = [pc + sep + '(.*?)' for pc in keyList]
rx = re.compile(''.join(rxPieces) + '$')
match = rx.match(inStr)
return dict(zip(kl, match.groups()))
def isKey(inStr):
rx = re.compile('(\w{5}-\w{5}-\w{5}-\w{5}-\w{5}-\w{5})')
return (rx.match(inStr) is not None)
s = "DATE: 12242010Key Type: Nod32 Anti-Vir (30d trial) Key: a5B2s-sH12B-hgtY3-io87N-srg98-KLMNO"
res = strToDict(s, ['DATE','Key Type','Key'], ': ')返回
{
'DATE': '12242010',
'Key': 'a5B2s-sH12B-hgtY3-io87N-srg98-KLMNO',
'Key Type': 'Nod32 Anti-Vir (30d trial) '
}和
if isKey(res['Key']):
print 'Found valid key'返回真
https://stackoverflow.com/questions/4525632
复制相似问题