求助python的字符串处理
需求:
文件a.txt内容如下
>> cat a.txt
/* ME Type=DEC, Version=V100R003C01*/
/* ME Type=NOV, Version=V100R003C00*/
/* ME Type=CCVS, Version=V100R003C03*/
/* ME Type=OCTOB, Version=V100R003C08*/
请问如何使用python脚本获取文件中的ME type,使之对数组a赋值:
a1=DEC
a2=NOV
a3=CCVS
a4=OCTOB
re.match
大侠,请帮忙写一个简单例子,刚开始学python,谢谢!
高级点这样:
Python code:
import re
reg = re.compile(r'Type=(\w*),')
def GetType(str):
match = reg.search(str)
if match is not None:
return match.groups(0)[0]
f = open('a.txt')
a = map(GetType, f)
print a
f.close()
当然如果你的数据相当规范,一定是以Type=为前导,也可以不用正则:
Python code:
import re
prefix = 'Type='
def GetType(str):
for i in str.split():
if i.startswith(prefix):
return i[len(prefix):-1]
f = open('a.txt')
a = map(GetType, f)
print a
f.close()
这只是举个例子,你对数据越了解,处理手段就越多。
re.findall('''Type=(.*?),''', str)
import re
f = open('t.txt')
相关问答:
s='aaa111aaa,bbb222,333ccc,444ddd444,555eee666,fff777ggg'
用正则表达式取出 前后字母相同的数据 结果如下:
111 ddd
谢谢~
Python code:
import re
s='aaa111aaa,bbb222,333ccc,444ddd444,555eee666,ff ......
大家好,我是一个新手,刚开始学python,但是刚开始的helloworld都没法打印,让我很无奈。
我的python安装路径为f:\python31。在path中也设置对了,在windows下运行是这样显示的,希望各位前辈指点一下。谢谢
Pyth ......
>>> x=-1
>>> if x>0:
print ('11')
>>> else:
SyntaxError: invalid syntax (<pyshell#20>, line 1)
网上搜的也是:
>>> x=int(input("Please ent ......