所有的名字都要在末尾精确匹配5位数字

2024-10-01 07:12:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的文本文件:

john123:
1
2
coconut_rum.zip

bob234513253:
0
jackdaniels.zip
nowater.zip 
3

judy88009:
dontdrink.zip
9

tommi54321:
dontdrinkalso.zip
92

...

我有数百万个这样的条目。在

我想取一个5位数长的名字和号码。我试过了:

^{pr2}$

但至少有5个数字。在

^{3}$

Q1:如何找到精确5位数字的名字?在

Q2:我想用5位数字附加与这些名称相关联的zip文件。如何使用正则表达式来实现这一点?在


Tags: 条目数字zip名字rum文本文件coconutjohn123
3条回答

这是因为\w包含数字字符:

>>> import re
>>> re.match('\w*', '12345')
<_sre.SRE_Match object at 0x021241E0>
>>> re.match('\w*', '12345').group()
'12345'
>>>

您需要更具体地告诉Python您只需要字母:

^{pr2}$

关于您的第二个问题,您可以使用以下内容:

import re
# Dictionary to hold the results
results = {}
# Break-up the file text to get the names and their associated data.
# filetext2.split('\n\n') breaks it up into individual data blocks (one per person).
# Mapping to str.splitlines breaks each data block into single lines.
for name, *data in map(str.splitlines, filetext2.split('\n\n')):
    # See if the name matches our pattern.
    if re.match('[A-Za-z]*\d{5}:', name):
        # Add the name and the relevant data to the file.
        # [:-1] gets rid of the colon on the end of the name.
        # The list comprehension gets only the file names from the data.
        results[name[:-1]] = [x for x in data if x.endswith('.zip')]

或者,没有所有的评论:

import re
results = {}
for name, *data in map(str.splitlines, filetext2.split('\n\n')):
    if re.match('[A-Za-z]*\d{5}:', name):
        results[name[:-1]] = [x for x in data if x.endswith('.zip')]

下面是一个演示:

>>> import re
>> filetext2 = '''\
... john123:
... 1
... 2
... coconut_rum.zip
...
... bob234513253:
... 0
... jackdaniels.zip
... nowater.zip
... 3
...
... judy88009:
... dontdrink.zip
... 9
...
... tommi54321:
... dontdrinkalso.zip
... 92
... '''
>>> results = {}
>>> for name, *data in map(str.splitlines, filetext2.split('\n\n')):
...     if re.match('[A-Za-z]*\d{5}:', name):
...         results[name[:-1]] = [x for x in data if x.endswith('.zip')]
...
>>> results
{'tommi54321': ['dontdrinkalso.zip'], 'judy88009': ['dontdrink.zip']}
>>>

但是请记住,一次读入文件的所有内容并不是很有效。相反,您应该考虑生成一个生成器函数,一次生成一个数据块。此外,还可以通过预编译正则表达式模式来提高性能。在

import re

results = {}

with open('datazip') as f:
    records = f.read().split('\n\n')

for record in records:
    lines = record.split()
    header = lines[0]

    # note that you need a raw string
    if re.match(r"[^\d]\d{5}:", header[-7:]):

        # in general multiple hits are possible, so put them into a list
        results[header] = [l for l in lines[1:] if l[-3:]=="zip"]

print results

输出

^{pr2}$

评论

我试图保持它非常简单,如果您的输入很长,那么您应该按照iCodez的建议,实现一个生成器,该生成器一次只能存储一条记录,而对于regexp匹配,我尝试了一点优化,只搜索头的最后7个字符。在

附录:记录生成器的简单实现

import re

def records(f):
    record = []
    for l in f:
        l = l.strip()
        if l:
            record.append(l)
        else:
            yield record
            record = []
    yield record

results = {}
for record in records(open('datazip')):
    head = record[0]
    if re.match(r"[^\d]\d{5}:", head[-7:]):
        results[head] = [ r for r in record[1:] if r[-3:]=="zip"]
print results

您需要将regex限制在单词的末尾,这样它就不会再使用\b匹配了

[a-zA-Z]+\d{5}\b

请参见示例http://regex101.com/r/oC1yO6/1

正则表达式会匹配的

^{pr2}$

python代码应该是

>>> re.findall(r'[a-zA-Z]+\d{5}\b', x)
['judy88009', 'tommi54321']

相关问题 更多 >