V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
ri0day
V2EX  ›  Python

python 正则表达式提取中文字符的问题

  •  
  •   ri0day ·
    ri0day · 2015-09-09 18:47:33 +08:00 · 5744 次点击
    这是一个创建于 3148 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我有一个文件里面包含了中英文以及中文标点,如下:(注意里面的冒号和括号是中文全角的)


    vagrant@vagrant-ubuntu-trusty-64:~/email_bot$ cat msg.txt
    开通数据库


    用户:xx盛源地产(1店)
    数据库文件:AgencyDByjsydc.rar
    vagrant@vagrant-ubuntu-trusty-64:~/email_bot$

    ----------------------------------------
    我希望输出
    {'title' : '开通数据库','client':'xx 盛源地产( 1 店)','db_data_file':'AgencyDByjsydc.rar'}

    我用正则折腾了好久,得不出想要的结果,请教大家
    4 条回复    2015-09-10 11:04:56 +08:00
    leavic
        1
    leavic  
       2015-09-10 00:52:21 +08:00
    为啥要正则,每行作为一个序列,第一行直接全部做 title ,后面的直接以“:” split 去[-1]项就行了啊
    ri0day
        2
    ri0day  
    OP
       2015-09-10 01:51:27 +08:00
    @leavic 忘记说明了。这个文本其实是一个邮件的 body,邮件有可能不按上面的文字顺序.也有可能会多一些文字.
    不过你的方法 对上面那个格式确实可以得到我要的效果.谢谢思路

    我最理想的方式是 类似 re.match ('用户:+(.*)',msg ).group ()这样
    ljdawn
        3
    ljdawn  
       2015-09-10 09:13:20 +08:00
    需要一个简单的文本状态机。 没匹配到另一个状态就继续。
    ri0day
        4
    ri0day  
    OP
       2015-09-10 11:04:56 +08:00
    借用楼上 2 个的思路,基本弄出来了
    #-coding:utf-8
    d={}
    with open ('msg2.txt','r') as f:
    for i in f.readlines ():
    if ':' not in i and not i.startswith ('\n'):
    title = i
    d['title'] = i
    elif i.isspace ():
    pass
    else:
    #print i.strip ()
    key , value = i.split (':')
    d[key] = value.strip ()

    for k, v in d.items ():
    print k.decode ('utf-8')+':'+v.decode ('utf-8')
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3964 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 10:21 · PVG 18:21 · LAX 03:21 · JFK 06:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.