我在找出解决此问题的方法时遇到了一些问题。
我想逐行读取文件并分析该行是否具有两个字符之一(1 或 0)。然后我需要总结该行的值并找到每个“1”字符实例的索引值(位置)。
例如:
1001
会导致:
line 1=(count:2, pos:[0,3])
我尝试了很多这样的变体:
r=urllib.urlopen(remote-resouce)
list=[]
for line in lines:
for m in re.finditer(r'1',line):
list.append((m.start()))
我有两个问题:
1) 我认为最好的解决方案是遍历每一行,然后使用正则表达式查找器函数。我这里的问题是我一直未能编写有效的 for 循环。尽管我尽了最大的努力,但我一直将结果作为一个长列表返回,而不是一个多维字典数组。
这种方法正确吗?如果是这样,我该如何编写正确的 for 循环?
如果没有,我还应该尝试什么?
最佳答案
也许不用正则表达式:
import urllib
url='http://stackoverflow.com/questions/5158168/python-regex-question/5158341'
f=urllib.urlopen(url)
for linenum,line in enumerate(f):
print(line)
locations=[pos for pos,char in enumerate(line) if char=='1']
print('line {n}=(count:{c}, pos:{l})'.format(
n=linenum,
c=len(locations),
l=locations
))
关于Python正则表达式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5158168/