简体   繁体   English

正则表达式python需要帮助

[英]Assistance needed for regex python

i have a file similar to that shown below- is it possible to perform a regex expression 我有一个类似于下面显示的文件 - 是否可以执行正则表达式

text1  769,230,123
text2  70
text3  213,445
text4  24,356
text5  1,2,4

to give output as shown here? 给出如此处所示的输出?

['769','230','123']
['70']
['213','445']

My current code is as follows: 我目前的代码如下:

with open(filename,'r') as output:
    for line in output:
        a = line
        a = a.strip()
        #regex.compile here
        print regex.findall(a)

Any help or direction would be greatly useful to me. 任何帮助或方向对我都非常有用。 Thank you 谢谢

看起来您可以找到所有数字序列:

regex = re.compile("[ ,]([0-9]+)")

The following regex will extract the comma separated numbers from the line, and then we can apply split(',') in order to extract the numbers: 以下正则表达式将从行中提取逗号分隔的数字,然后我们可以应用split(',')来提取数字:

import re
line = "text1  769,230,123"
mat = re.match(r'.*? ([\d+,]+).*', line)
nums = mat.group(1).split(',')
for num in nums:
    print num

OUTPUT OUTPUT

769
230
123

The following should work for you. 以下内容适合您。

>>> import re
>>> regex = re.compile(r'\b\d+\b')
>>> with open(filename, 'r') as output:
...     for line in output:
...         matches = regex.findall(line)
...         for m in matches:
...             print m

Output 产量

769
230
123
70
213
445
24
356
1
2
4

You don't need regular expressions for this. 您不需要正则表达式。 Just line.split(',') . 只是line.split(',')

Assuming you always have 2 spaces between text# and your comma separated values. 假设text#和逗号分隔值之间总是有2个空格。 Here's a simple way to extract the separated values into arrays 这是将分离的值提取到数组中的简单方法

list = []
with open(filename,'r') as output:
    for line in output:
        line = line.strip('  ')
        list.append(line[1].strip(','))

This will produce a nested list 这将生成一个嵌套列表

print list[0] #['769','230','123']
print list[1] #['70']
print list[2] #['213','445']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM