python - 匹配末尾正好 5 位数字的所有名称

标签 python regex file

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

john123:
1
2
coconut_rum.zip

bob234513253:
0
jackdaniels.zip
nowater.zip 
3

judy88009:
dontdrink.zip
9

tommi54321:
dontdrinkalso.zip
92

...

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

我想提取 5 位数字长的姓名和号码。我试过这个:

matches = re.findall(r'\w*\d{5}:',filetext2)

但它给我的结果至少 5 位数字。

['bob234513253:', 'judy88009:', 'tommi54321:']

问题1:如何查找正好 5 位数字的姓名?

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

最佳答案

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

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

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

matches = re.findall(r'[A-Za-z]*\d{5}:',filetext2)

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

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']}
>>>

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

关于python - 匹配末尾正好 5 位数字的所有名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26831806/

相关文章:

python - 正则表达式匹配字符串 "Hello, name"

regex - 返回两个字符之间的文本

c - 获取由 mkstemp() 创建的文件名

Azure 存储文件 "Authentication scheme Bearer is not supported." "AuthenticationFailed"

python - Tensorflow "Hello World"示例在 PyCharm 中不起作用

python - 在名称已更改的列中查找唯一值时出现 Pandas 错误

java - startsWith endsWith 匹配包含正则表达式

python - 如何使用Python从特定位置读取文件到特定位置?

python - 删除 Pandas Dataframe 列范围内每列总和小于 10 的列

python - Pandas :在约束下对每对列应用函数